简体   繁体   中英

Join one to many with multiple where

This is products table:

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

This is product_filter table:

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

i want if where product_filter.filter_id = 1 and product_filter.filter_id = 2 the result of product.id is 1 and 2

if where product_filter.filter_id = 1 and product_filter.filter_id = 3 the result of product.id is 1 and 3

This is my query, and it's not works:

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'

Instead of AND use 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);

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