MySQL查询左连接问题
我有两张桌子:MySQL查询左连接问题,mysql,sql,join,relational-database,Mysql,Sql,Join,Relational Database,我有两张桌子: product table product_id product_name 1 sample1 2 sample2 3 sample3 product_child table pc_id product_id product_size 1 1 5 2 1 6 3 1
product table
product_id product_name
1 sample1
2 sample2
3 sample3
product_child table
pc_id product_id product_size
1 1 5
2 1 6
3 1 7
4 2 5
5 2 8
6 2 7
7 3 8
8 3 6
9 3 9
我的问题是:我想购买产品尺寸(5或9)和6的所有产品。
这意味着我想要的结果是:
product_id product_name
1 sample1
3 sample3
我需要这样的查询:
SELECT p.*
FROM products p
LEFT JOIN product_child pc
ON pc.product_id = p.product_id
WHERE ( pc.product_size = 5 OR pc.product_size = 9)
AND pc.product_size = 6
但它不起作用
WHERE pc.product_size = 5
AND pc.product_size = 6
用或替换和,它将是正确的。尝试以下查询:
SELECT p.*
FROM products p
JOIN product_child pc1 ON pc1.product_id = p.product_id and pc1.product_size in (5,9)
JOIN product_child pc2 ON pc2.product_id = p.product_id and pc2.product_size = 6
如果我理解正确,您需要两种尺寸的所有产品。
所以你有不同的产品,每种产品都有不同的尺寸。而且您只需要同时出现(5或9)和6种尺寸的产品。
我想你需要这样的东西:
SELECT * from products where product_id IN
( SELECT product_id from product_child where product_size = 5 or product_size = 9
INTERSECT
SELECT product_id from product_child where product_size = 6
)
在上面的查询中,我进行了交叉。我选择了一套(5号或9号的产品)和第二套(6号的产品)。
相交意味着找到两个集合中出现的产品。您是想要
还是?product\u size
怎么能同时等于5和6…我需要“和”条件和“或”条件都需要