在FK上具有多个条件的Mysql查询

时间:2014-04-16 07:16:53

标签: mysql

我的mysql查询有点问题。我有两张桌子:

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            |
+----+-----------------+--------------+

表格要复杂得多,但这是重要的结构。 bioshop_have_product中的prodict_id也是FK。我需要选择bioshops女巫包含我问的所有产品。例如:

  • 如果我需要使用产品1的bioshops,它应该返回所有产品的Bioshop1和Bioshop2

  • 如果我需要使用产品1和产品2进行bioshop,它应该返回所有产品的Bioshop1

我的查询是:

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')

但是这没有返回任何内容,我希望它返回Bioshop1,因为只有Bioshop1才会返回两个对象。

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

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

其中X应该等于您要检查的不同产品的数量,例如在第二种情况下为2。

答案 1 :(得分:0)

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