SELECT tasks.name,date_due, tasks.description,
CASE WHEN parent_Type = 1 then
accounts.name
WHEN parent_Type=2 then
leads.name
END as Name
FROM tasks
LEFT JOIN accounts
on tasks.parent_id = accounts.id
LEFT JOIN leads
on leads.id = tasks.parent_ID
WHERE DATE(date_due) = DATE(NOW() + INTERVAL 1 DAY) AND tasks.assigned_user_id=1
或者,如果您知道 ID 不会出现在两个表之一中,则 coleaease 将起作用。Coalease 采用系列中的第一个非空值。
SELECT tasks.name,date_due, tasks.description,
coalesce(accounts.name, leads.name) as Name
FROM tasks
LEFT JOIN accounts
on tasks.parent_id = accounts.id
LEFT JOIN leads
on leads.id = tasks.parent_ID
WHERE DATE(date_due) = DATE(NOW() + INTERVAL 1 DAY) AND tasks.assigned_user_id=1
否则,必须编写动态 SQL 以动态调整表名:一个示例是:
EXECUTE IMMEDIATE concat("select * from ", @table_name, " where a=", @val);
如发现http://dev.mysql.com/worklog/task/?id=2793。
但是,我会提醒您注意这种方法,因为它会受到 SQL 注入机会的影响,而没有适当的控制来传递传入的变量。