mysql用if语句连接三个表

时间:2012-06-11 10:30:36

标签: mysql join

我有一个正在运行的查询

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;

2 个答案:

答案 0 :(得分: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。

答案 1 :(得分: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的子句放入连接中。