在 SQL 语句中使用 IF
Using IF In SQL Statement
如何根据条件创建 sql 语句?
select Name, Address, Flag from Employees
If Flag = 'Y' then
join Customers
on id=id
else
join Clients
on id=id
对于返回的每条记录,我想加入 Customers 或 Clients table 以获取更多信息
一种方法
SELECT e.Name,
e.Address,
e.Flag,
CASE
WHEN e.flag = 'Y'
THEN c.some_column
ELSE l.other_column
END AS additional_info
FROM Employees e
LEFT JOIN Customers c
ON e.id = c.employee_id
AND e.flag = 'Y'
LEFT JOIN Clients l
ON e.id = l.employee_id
AND e.flag = 'N'
这是一个SQLFiddle演示
使用两个不同的 select 查询并将结果与 Union all
合并
SELECT NAME,
Address,
Flag
FROM Employees e
JOIN Customers c
ON e.id = c.id
AND e.Flag = 'Y'
UNION ALL
SELECT NAME,
Address,
Flag
FROM Employees e
JOIN Clients c
ON e.id = c.id
AND (e.Flag IS NULL OR e.Flag <> 'Y')
如何根据条件创建 sql 语句?
select Name, Address, Flag from Employees
If Flag = 'Y' then
join Customers
on id=id
else
join Clients
on id=id
对于返回的每条记录,我想加入 Customers 或 Clients table 以获取更多信息
一种方法
SELECT e.Name,
e.Address,
e.Flag,
CASE
WHEN e.flag = 'Y'
THEN c.some_column
ELSE l.other_column
END AS additional_info
FROM Employees e
LEFT JOIN Customers c
ON e.id = c.employee_id
AND e.flag = 'Y'
LEFT JOIN Clients l
ON e.id = l.employee_id
AND e.flag = 'N'
这是一个SQLFiddle演示
使用两个不同的 select 查询并将结果与 Union all
SELECT NAME,
Address,
Flag
FROM Employees e
JOIN Customers c
ON e.id = c.id
AND e.Flag = 'Y'
UNION ALL
SELECT NAME,
Address,
Flag
FROM Employees e
JOIN Clients c
ON e.id = c.id
AND (e.Flag IS NULL OR e.Flag <> 'Y')