2012-06-11 94 views
0

我已經得到了的工作MySQL的加入三個表if語句

SELECT * 
FROM the_index AS t1 
LEFT JOIN table_2 AS t2 ON (t1.activity_id = t2.id) 
LEFT JOIN table_3 AS t3 ON (t1.activity_id = t3.id) 
ORDER BY t1.id; 

工作正常的查詢,但我想用一些if語句來修改它..

SELECT * 
FROM the_index AS t1 
LEFT JOIN table_2 AS t2 ON (t1.activity_id = t2.id)  <---- If t1.event = '2' 
LEFT JOIN table_3 AS t3 ON (t1.activity_id = t3.id)  <---- If t1.event = '3' 
ORDER BY t1.id; 
+0

解釋更好。你想執行一個連接或另一個關於't1.event'的值? – Cranio

回答

1

只需使用這:

LEFT JOIN table_2 AS t2 ON (t1.activity_id = t2.id AND t1.event = '2') 
LEFT JOIN table_3 AS t3 ON (t1.activity_id = t3.id AND t1.event = '3') 

請注意,這隻有在使用LEFT JOIN時才起作用。不適用於INNER JOIN。

0

你的意思

SELECT * 
FROM the_index AS t1 
LEFT JOIN table_2 AS t2 ON (t1.activity_id = t2.id AND t1.event = '2') 
LEFT JOIN table_3 AS t3 ON (t1.activity_id = t3.id AND t1.event = '3') 
ORDER BY t1.id; 

警告:這明確違背了MySQL的建議,不要把WHERE樣的條款轉換爲連接。

+0

任何理由都不鼓勵? –