MySQL在案例中加入不同的表

时间:2017-07-19 10:15:55

标签: mysql sql join case

我试图加入一个不同的表取决于" task_type"的价值。柱

语法有什么问题? 感谢。

SELECT t.*,s.task_name
    CASE
    WHEN t.task_type = 0 THEN
    LEFT JOIN scheduler_tasks s ON s.scheduler_task_id = t.task_id
    WHEN t.task_type = 1 THEN 
    LEFT JOIN invoice_tasks s ON s.uid = t.task_id 
    END 
    FROM task_timings t 
    WHERE t.account_id = ? AND t.start_date >= DATE(?) AND t.start_date <= DATE(?)

2 个答案:

答案 0 :(得分:0)

你可以尝试这样:

SELECT t.*,s.task_name FROM task_timings t 
CASE
WHEN t.task_type = 0 THEN
LEFT JOIN scheduler_tasks s ON s.scheduler_task_id = t.task_id
WHEN t.task_type = 1 THEN 
LEFT JOIN invoice_tasks s ON s.uid = t.task_id 
END 
    WHERE t.account_id = ? AND t.start_date >= DATE(?) AND t.start_date <= DATE(?)

答案 1 :(得分:0)

我相信你想要这个:

SELECT t.*,
       COALESCE(s.task_name, i.task_name) as task_name
FROM task_timings t LEFT JOIN
     scheduler_tasks s
     ON s.scheduler_task_id = t.task_id AND 
        t.task_type = 0 LEFT JOIN
     invoice_tasks i
     ON i.uid = t.task_id AND t.task_type = 1
WHERE t.account_id = ? AND t.start_date >= DATE(?) AND
      t.start_date <= DATE(?);