在SQL语句中使用IF

时间:2015-01-01 17:52:25

标签: sql

如何根据条件创建sql语句?

select Name, Address, Flag from Employees
If Flag = 'Y' then 
join Customers 
on id=id
else
join Clients
on id=id

对于返回的每条记录,我想要加入Customers或Clients表以获取更多信息

2 个答案:

答案 0 :(得分:1)

一种方法

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 演示

答案 1 :(得分:1)

使用两个不同的选择查询,并将结果与​​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')