2017-07-19 59 views
0

我試圖加入一個依賴於「task_type」列的值的不同表格MySQL加入不同的表格

語法有什麼問題? 謝謝。

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(?) 
+0

可以顯示錯誤? – Jenish

+0

'FROM'必須在'LEFT JOIN'之前。 – 2017-07-19 10:18:15

+0

@aendeerei之前,同樣的錯誤你的SQL語法有錯誤;檢查與您的MariaDB服務器版本相對應的手冊,查看'CASE WHEN t.task_type = 0 then THEN LEFT JOIN scheduler_tasks s ON s.scheduler_task'at line 2,driver error code is 1064 – Dunams

回答

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(?); 
+0

謝謝!一個小的調整是ON s.uid - 需要是ON i.uid – Dunams

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(?) 
+0

Same - You have an您的SQL語法錯誤;檢查與您的MariaDB服務器版本相對應的手冊,以便在第2行「CASE WHEN t.task_type = 0 THEN LEFT JOIN scheduler_tasks s ON s.scheduler_task」時使用正確的語法,驅動程序錯誤代碼爲1064 – Dunams