I have two tables user
and product
which have a one-to-many relationship (one user
may have multiple product
s).
I want to create a query to get all user
s which have both an orange and a banana. In my example below this would be john
and leeroy
.
How can I formulate my query to do that?
With only one condition I would go like:
SELECT * FROM "user"
INNER JOIN "product" ON "product"."fk_user" = "user"."id"
WHERE "product"."product" = 'banana';
The user
table
╔════╦═════════╗
║ id ║ name ║
╠════╬═════════╣
║ 1 ║ michael ║
╠════╬═════════╣
║ 2 ║ john ║
╠════╬═════════╣
║ 3 ║ leeroy ║
╠════╬═════════╣
║ 4 ║ tony ║
╚════╩═════════╝
The product
table
╔═════════╦═════════╗
║ product ║ fk_user ║
╠═════════╬═════════╣
║ orange ║ 1 ║
╠═════════╬═════════╣
║ orange ║ 2 ║
╠═════════╬═════════╣
║ banana ║ 2 ║
╠═════════╬═════════╣
║ banana ║ 3 ║
╠═════════╬═════════╣
║ orange ║ 3 ║
╠═════════╬═════════╣
║ banana ║ 4 ║
╚═════════╩═════════╝