在多个地方加入一对多

时间:2017-11-07 04:28:08

标签: mysql join where

这是产品表:

+-----------+
| id | name |
+-----------+
| 1  | A    | 
+-----------+
| 2  | B    | 
+-----------+
| 3  | C    | 
+-----------+ 

这是product_filter表:

+-----------------+-----------+
| id | product_id | filter_id |
+-----------------+-----------+
| 1  | 1          | 1         |
+-----------------------------+
| 2  | 1          | 2         |
+-----------------------------+ 
| 3  | 2          | 1         |
+-----------------------------+
| 4  | 2          | 2         |
+-----------------------------+
| 5  | 2          | 3         |
+-----------------------------+
| 6  | 3          | 1         |
+-----------------------------+
| 7  | 3          | 3         |
+-----------------------------+

我想知道如果product_filter.filter_id = 1且product_filter.filter_id = 2 product.id的结果是1和2

如果product_filter.filter_id = 1且product_filter.filter_id = 3,则product.id的结果为1和3

这是我的查询,但不起作用:

SELECT `products`.`id`, `product_filter`.`filter_id`
FROM `products` 
JOIN `product_filter` ON `product_filter`.`product_id` = `products`.`id` 
WHERE `product_filter`.`filter_id` = '1' AND `product_filter`.`filter_id` = '2'

1 个答案:

答案 0 :(得分:1)

而不是AND使用IN

SELECT
    p.id,
    pf.filter_id
FROM products p
INNER JOIN product_filter pf
    ON pf.product_id = p.id
WHERE
    pf.filter_id IN (1, 2);