Click here to Skip to main content
15,910,886 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)

I have table related to two tables which is a many to many relationship. For eg: I have a user, product and userproducts table that contains these columns:



User
id
username
email
lastname

Product
id
userid int foreign key references user(id)
name
quantity

Userproducts
id
userid int foreign key references user(id)
productid int foreign key references Product(id)



Now, how do i get the username, last name and product name from the users and products table respectively that does not exist in the Userproducts table.

I have a method that list all the users products from the Userproductstable, but it is really giving me a tough time to get it the other way around.



Please, any help on how to do this either in EF or pure sql query. Thanks

Posted
Updated 7-Apr-15 9:30am
v2
Comments
Maciej Los 7-Apr-15 16:10pm    
What have you tried? Where are you stuck?

1 solution

Hello,

If I understood you correctly, you need all combinations of users and products that doesn't exist in Userproducts table?

If that is correct, then this query should give you all required results:

SQL
Select u.username, u.lastname, p.name
From User as u, Product as p
Where not exists 
(Select * From Userproducts as up Where up.userid=u.id and up.productid=p.id)


If what you require is separately for users and for products, then it is even easier:
Users:
SQL
Select u.username, u.lastname
From User as u
Where u.id not in
(Select up.userid From Userproducts)


Products:
SQL
Select p.name
From Product as p
Where p.id not in
(Select up.productid From Userproducts)



Hope it helped.
Regards,
 
Share this answer
 
Comments
Member 10250878 20-Apr-15 15:48pm    
I just forget about the "where not exists" syntax. Anyways, i created a stored procedure for it and i used EF to call it.

Regards.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900