我对这个问题有一点脑力障碍,我发现很难找到解决方案,因为我无法正确地说出问题以提出相关信息。
我试图从下表中找回“fAroduct”记录,其中有“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
有人可以帮忙吗?
答案 0 :(得分:3)
您可以使用INNER JOINS或使用EXISTS条件:
INNER JOIN:
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
EXISTS:
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)
答案 1 :(得分:1)
联接应该有所帮助:
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
答案 2 :(得分:0)
由于您已经在进行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