这些表如下所示:
Table: Shops ShopCode ShopName -------- -------- A Aladdin B Backstreet C Clerk's Store D Debs Tool Table: Sale ShopCode Product -------- ------- A Hammer A Thermometer A Compass B Eraser B Hammer C Thermometer C Hammer D Thermometer
查找同时出售锤子和温度计的商店的名称。结果表将是
ShopName -------------- Aladdin Clerk's Store
我以为下面的查询可以用,但是返回的空集
mysql> SELECT Shops.ShopName FROM Shops -> JOIN Sale ON Shops.ShopCode=Sale.ShopCode -> WHERE Sale.Product='Hammer' AND Sale.Product='Thermometer' -> GROUP BY Shops.ShopCode;
也尝试用OR代替AND,但不起作用(退还所有商店)。有什么可能的解决方案?
为了更清楚一点,我想选择同时包含商品(锤子和热电偶)的商店,即使商店B出售锤子而商店D出售温度计,也将不包括在内。只有同时出售这两种商品的A和C才会出现在结果上
有两个相当简单的选择。
您可以在销售表中加入两次,每个项目一次。如果您跳过DISTINCT,则如果商店出售多个锤子或温度计,则可能会得到重复的值。
DISTINCT
SELECT DISTINCT s.shopname FROM shops s JOIN sale s1 ON s.shopcode = s1.shopcode AND s1.product='hammer' JOIN sale s2 ON s.shopcode = s2.shopcode AND s2.product='thermometer';
…或者您可以用锤子或温度计找到所有匹配项,并计算有多少个不同的值。如果有两个可能的值,而您同时获得了两个,则表示已设置。
SELECT s.shopname FROM shops s JOIN sale s1 ON s.shopcode = s1.shopcode WHERE s1.product IN('hammer','thermometer') GROUP BY s.shopname HAVING COUNT(DISTINCT s1.product)=2;
一个SQLfiddle来测试两者。