2012-01-26 89 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