MySQL LEFT JOIN与IF

时间:2016-08-25 06:20:47

标签: mysql

我有这个问题:

SELECT r.*, d.rateName
FROM ratings r
LEFT JOIN rate_data d ON (r.rateID=d.rateID AND d.rateName != '')
ORDER BY r.rateTime DESC

这项工作很好。现在我有第二个数据表。在一个查询中使用IF进行更改,或者是进行两次查询并合并结果的唯一方法吗?

我试着告诉你我的意思:

SELECT r.*, d.rateName
FROM ratings r
(IF r.isOther == 0)LEFT JOIN rate_data d ON (r.rateID=d.rateID AND d.rateName != '')
(ELSEIF r.isOther == 1)LEFT JOIN rate_data_other d ON (r.rateOtherID=d.rateOtherID AND d.rateName != '')
ORDER BY r.rateTime DESC

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

SELECT r.*, IF(r.isOther,do.rateName,d.rateName)
FROM ratings r
LEFT JOIN rate_data d ON (r.rateID = d.rateID AND d.rateName != '')
LEFT JOIN rate_data_other do ON (r.rateOtherID = do.rateOtherID AND do.rateName != '')
ORDER BY r.rateTime DESC;

或者

SELECT r.*, 
(CASE 
 WHEN r.isOther = 0 THEN d.rateName
 ELSE do.rateName
 END) as rateName
FROM ratings r
LEFT JOIN rate_data d ON (r.rateID = d.rateID AND d.rateName != '')
LEFT JOIN rate_data_other do ON (r.rateOtherID = do.rateOtherID AND do.rateName != '')
ORDER BY r.rateTime DESC;