2

我有一个这样的mysql表

PRODUCT
-------
product_id: 1 | name: product .... product_id: 2 | name: product2 .. etc etc

然后我有另一张桌子

PROPERTY
---
id: 1 | name: red | product_id: 1 .... id: 2 | name: large | product_id: 1 ..... id: 3 | name : brown | product_id: 2 .... and so on ...

如何选择具有 2 个属性的产品?

例如,我想购买具有 RED 和 LARGE 属性的产品

我试过

SELECT * FROM product
JOIN property USING (product_id)
WHERE property.name = "red" AND property.name = "large" ....

但显然它不起作用:)

感谢您的帮助,对不起我的英语!

4

3 回答 3

2

你需要计算它的记录实例

SELECT  a.productname
FROM    product a
        INNER JOIN property b
            on a.product_ID = b.product_ID
WHERE b.name IN ('red', 'large')
GROUP BY a.productname
HAVING COUNT(a.productname) = 2

如果您单击演示,您可以看到分组结果和使用常规过滤器之间的差异IN

SQLFiddle 演示

于 2012-09-06T14:43:15.127 回答
0

你应该使用OR

SELECT * FROM product
JOIN property USING (product_id)
WHERE property.name = "red" OR property.name = "large" ....

此外,您可以使用IN

SELECT * FROM product
JOIN property USING (product_id)
WHERE property.name IN ('red', 'large') ....
于 2012-09-06T14:41:23.077 回答
0

也许像

SELECT p.* 
  FROM product p
 WHERE EXISTS( SELECT * 
                 FROM property a
                WHERE a.name = 'red' 
                  AND a.product_id = p.product_id)
   AND EXISTS( SELECT * 
                 FROM property a
                WHERE a.name ='large' 
                  AND a.product_id = p.product_id)

可以工作吗?

于 2012-09-06T14:44:14.897 回答