[英]Howto Select rows that match the intersection of multiple rows in other tables in MYSQL?
[英]Match on multiple rows in child tables with MySQL
我有一個名為Product的表和一個名為ProductProperty的子表:
Product(Product_id, productName,...)
ProductProperty(id, propertyKey, propertyValue, Product_id)
因此,一個產品可以具有多個對應的ProductProperty行。
現在,我要查詢以下內容:'選擇所有屬性width = 12和height = 35的產品行'。 對於這個特定示例,我提出了以下查詢,該查詢可以正常工作,但是我覺得我可能缺少一個好的解決方案。
SELECT Product.Product_id from Product
WHERE
EXISTS (SELECT * FROM ProductProperty WHERE propertyKey='width' AND propertyValue='12' AND ProductProperty.Product_id = Product.Product_id)
AND
EXISTS (SELECT * FROM ProductProperty WHERE propertyKey='height' AND propertyValue='35' AND ProductProperty.Product_id = Product.Product_id);
我在這里缺少任何明顯更好的實現嗎?
這個怎么樣:
SELECT p.Product_id
FROM Product p
JOIN ProductProperty pp ON p.Product_id = pp.Product_id
WHERE (pp.propertyKey = 'width' AND pp.propertyValue = '12')
OR (pp.propertyKey = 'height' AND pp.propertyValue = '35')
GROUP BY p.Product_id
HAVING COUNT(*) = 2;
當然,這假定產品不能具有重復的密鑰。 如果有可能,您可以嘗試以下方法:
SELECT p.Product_id
FROM Product p
JOIN ProductProperty pp ON p.Product_id = pp.Product_id
GROUP BY p.Product_id
HAVING SUM(pp.propertyKey = 'width' AND pp.propertyValue = '12') > 0
AND SUM(pp.propertyKey = 'height' AND pp.propertyValue = '35') > 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.