【问题标题】:MySQL JOIN WHERE forgein Key = id1 AND forgein Key = id2MySQL JOIN WHERE 外键 = id1 AND 外键 = id2
【发布时间】:2012-01-27 02:47:02
【问题描述】:

我对这个问题有点脑残,我发现很难找到解决方案,因为我无法正确地表达问题以提供相关信息。

我正在尝试从下表中取回“fProduct”记录,该记录具有“fAttribute” 2 和 20。

id  fAttribute  fProduct
19      2        2967
48      2        2923
50      2        3008
51      20       3008
52      2        2295
53      20       2295

当我期望返回 fProduct 的 2295 和 3008 时,我的以下语句产生 0 个结果。

SELECT fProduct 
FROM  tableName 
WHERE fAttribute = 2 AND fAttribute = 20
GROUP BY fProduct

有人可以帮忙吗?

【问题讨论】:

    标签: mysql join


    【解决方案1】:

    您可以使用 INNER JOINS 或使用 EXISTS 条件:

    内连接:

    SELECT DISTINCT a.fProduct
    FROM MyTable a
         INNER JOIN MyTable b ON a.fProduct = b.fProduct AND b.fAttribute = 2
         INNER JOIN MyTable c ON a.fProduct = c.fProduct AND c.fAttribute = 20
    

    存在:

    SELECT afproduct
    FROM MyTable a
    WHERE EXISTS (SELECT b.id FROM MyTable b WHERE a.fProduct = b.fProduct AND b.fAttribute = 2)
      AND EXISTS (SELECT c.id FROM MyTable c WHERE a.fProduct = c.fProduct AND c.fAttribute = 20)
    

    【讨论】:

    • Wicked 我最后使用了“内连接”选项。干杯第一哥们。
    • @TheoKouzelis 很高兴我能帮上忙!!
    【解决方案2】:

    加入应该会有所帮助:

    SELECT distinct a.fProduct 
    FROM  tableName as a
    join tableName as b on b.product = a.product
    WHERE a.fAttribute = 2 and  b.fAttribute = 20
    

    【讨论】:

    • 您在 where 子句中的 and 之前缺少 = 2
    【解决方案3】:

    由于您已经在执行GROUP BY,只需将您的WHERE 子句更改为OR 或IN 并添加HAVING COUNT(fattribute) = 2,以确保两者兼有。

    SELECT fproduct 
    FROM   tablename 
    WHERE  fattribute IN (2 , 20)
    GROUP  BY fproduct 
    HAVING COUNT(fattribute) = 2 
    

    【讨论】:

      猜你喜欢
      • 2015-07-12
      • 2011-08-13
      • 2019-06-19
      • 2019-06-09
      • 2011-06-28
      • 2017-06-13
      • 1970-01-01
      • 2020-06-15
      相关资源
      最近更新 更多