MySQL选择This和That

时间:2014-02-19 20:37:04

标签: mysql sql database

表格如下:

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

找到销售BOTH Hammer和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应该在结果上

3 个答案:

答案 0 :(得分:6)

有两个相当直接的选择。

您可以使用促销表加入两次,每件商品一次。如果您跳过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;

An SQLfiddle to test both

答案 1 :(得分:2)

您可以轻松地在Sale表上加入两次 - 一次用于锤子,一次用于温度计,以便与两个锤子和Theremoeteres一起获得商店

 SELECT s.ShopName FROM Shops s  
      JOIN Sale s1 ON s.ShopCode=s1.ShopCode AND s1.Product='Thermometer'
      JOIN Sale s2 ON s1.ShopCode=s2.ShopCode AND s2.Product='Hammer'
  GROUP BY s.ShopName

答案 2 :(得分:-3)

我认为正确的Sql看起来像这样:

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

mysql> SELECT Shops.ShopName FROM Shops
    -> JOIN Sale ON Shops.ShopCode=Sale.ShopCode
    -> WHERE Sale.Product IN ('Hammer', 'Thermometer')
    -> GROUP BY Shops.ShopCode;