2014-07-24 84 views
0

我有一個看起來像這樣的表:簡化MySQL查詢 - 2個查詢到1

+----+--------+-------+ 
| id | entity | word | 
+----+--------+-------+ 
| 1 |  1 | red | 
| 2 |  1 | green | 
| 3 |  1 | blue | 
| 4 |  2 | car | 
| 5 |  2 | truck | 
| 6 |  2 | train | 
| 7 |  3 | water | 
| 8 |  3 | milk | 
| 9 |  3 | soda | 
+----+--------+-------+ 

如果我做blue搜索我想獲得red,​​和blue作爲一個答案。現在我正在使用2個查詢。一個找到'實體'號碼,一個找到具有相同'實體'號碼的所有單詞。

回答

2

試試這個。加入比子查詢快得多

select distinct t2.word from Table t1 
INNER JOIN Table t2 on t2.entity=t1.entity 
where t1.word="blue"; 
1
SELECT * 
FROM TABLE_NAME 
WHERE entity IN 
    (SELECT entity 
    FROM TABLE_NAME 
    WHERE word='blue');