0

我有一个有效的查询

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;
4

2 回答 2

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。

于 2012-06-11T10:34:40.407 回答
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-like 子句放入连接中。

于 2012-06-11T10:34:52.697 回答