2012-01-26 120 views
1

我对这个问题有一点脑块,我发现很难搜索解决方案,因为我不能正确地提出问题来调出相关问题信息。MySQL JOIN WHERE forgein Key = id1 AND forgein Key = id2

我试图从表中取回“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 

下面我statment产生0结果时,我会希望返回fProduct的2295和3008.

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

任何人都可以帮忙吗?

回答

3

您可以使用内部连接或使用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 

存在:

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) 
+0

+1:快一分钟。 –

+0

邪恶我在最后使用了“内部连接”选项。干杯最好的一个家伙。 –

+0

@TheoKouzelis很高兴我可以帮助! –

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 
+1

你在'和'之前缺少'= 2'在你的where子句中 –

+0

感谢你的提示,纠正了它。 –

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