简体   繁体   中英

Mysql query with multiple conditions on FK

I have slight problem with mysql query. I have two tables:

bioshops

+------------+-------------+
| bioshop_id | name        |
+------------+-------------+
| 1          | Bioshop1    | 
| 2          | Bioshop2    |
+------------+-------------+

bioshop_have_product

+----+-----------------+--------------+
| id | bioshop_id      | product_id   |
+----+-----------------+--------------+
| 1  | 1               | 1            |
| 2  | 1               | 2            |
| 3  | 2               | 1            |
| 4  | 2               | 3            |
+----+-----------------+--------------+

The tables are much more complex but this is the important structure. prodict_id in bioshop_have_product is also FK. I need to select bioshops witch contains all products that I ask. Example:

  • if I need bioshops with product 1 it should return Bioshop1 and Bioshop2 with all products

  • if I need bioshops with product 1 and 2 it should return Bioshop1 with all products

My query is:

SELECT bs.name AS name,
bs.id AS bioshop_id,
bshd.id AS id,
bshd.product_id AS product_id
FROM bioshops bs
JOIN bioshop_have_product bshp
ON bs.bioshop_id = bshp.bioshop_id
WHERE (bshp.bioshop_id = bs.bioshop_id AND bshp.product_id = '1')
AND (bshp.bioshop_id = bs.bioshop_id AND bshp.product_id = '2')

but this returns nothing and I want it to return Bioshop1 because only Bioshop1 countains both objects.

You can try something like this:

SELECT bs.name AS name,
 bs.id AS bioshop_id,
 bshp.id AS id,
 bshp.product_id AS product_id
FROM bioshop bs
JOIN bioshop_have_product bshp
ON bs.id = bshp.bioshop_id AND 
 (SELECT COUNT(*) FROM bioshop_have_product WHERE product_id IN (1, 2) AND bs.id = bioshop_id) = X

where X should be equal to the count of different products you whant to check, for instance 2 in your second case.

SELECT bioshop_id 
  FROM bioshop_have_product
 WHERE product_id IN (1,2) 
 GROUP 
    BY bioshop_id 
HAVING COUNT(*) = 2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM