条件JOIN不同的表

时间:2012-04-23 10:49:13

标签: sql sql-server-2008 join conditional

我想知道用户是否在2个相关表的任意中有条目。

表格

USER (user_id)
EMPLOYEE (id, user_id)
STUDENT (id, user_id)

用户可能有员工和/或学生条目。如何在一个查询中获取该信息? 我试过了:

select * from [user] u
inner join employee e 
    on e.user_id = case when e.user_id is not NULL 
                        then u.user_id 
                        else null 
                   end
inner join student s 
    on s.user_id = case when s.user_id is not NULL 
                        then u.user_id 
                        else null 
                   end

但它只会返回两个表中的条目的用户。

SQL Fiddle example

6 个答案:

答案 0 :(得分:20)

您可以使用外部联接:

select *
  from USER u
  left outer join EMPLOYEE e ON u.user_id = e.user_id
  left outer join STUDENT s ON u.user_id = s.user_id
 where s.user_id is not null or e.user_id is not null

或(如果您对EMPLOYEE或STUDENT表中的数据不感兴趣)

select *
  from USER u
 where exists (select 1 from EMPLOYEE e where e.user_id = u.user_id)
    or exists (select 1 from STUDENT s  where s.user_id = u.user_id)

答案 1 :(得分:8)

如果您想要将所有用户数据放在一起您可能拥有:

SELECT 
    user_id
    ,'Employee' AS Source
FROM 
    employee
UNION 
SELECT 
    user_id
    ,'Student' AS Source
FROM 
    student

http://sqlfiddle.com/#!3/90216/22

使用完整连接和CASE语句也可以完成:

SELECT 
    ISNULL(e.user_id,s.user_id) AS user_id
    ,CASE WHEN e.user_id IS NULL THEN 'Student' 
        ELSE 'Employee'
    END AS SOURCE
FROM 
    employee AS e 
    FULL JOIN student AS s
        ON s.user_id = e.user_id

http://sqlfiddle.com/#!3/90216/29

后者会将同时兼顾员工的人员​​组合成一行,并将他们称为员工。比较:

http://sqlfiddle.com/#!3/2aa3e/1http://sqlfiddle.com/#!3/2aa3e/2

我将用户1作为学生和员工

答案 2 :(得分:4)

这样的解决方案也可以帮到你。

SELECT  S.*, P.*

,CASE
    WHEN S.ShipmentType = 'import' THEN SP.SupplierName
    WHEN S.ShipmentType = 'export' THEN C.CustomerName
END AS ShipmentDesination

FROM            tblShippments   S 
INNER JOIN      tblProducts     P   ON S.productId = P.productID  
LEFT OUTER JOIN tblCustomers    C   ON S.companyId = C.customerId AND S.ShipmentType = 'export'
LEFT OUTER JOIN tblSuppliers    SP  ON S.companyId = SP.supplierId AND S.ShipmentType = 'import'

答案 3 :(得分:2)

如果您将员工和学生表视为一个,则可以使用左连接:

select * 
from user u
left join 
(
   select 'Employee' as UserType,
          id,
          user_id
     from employee e 
    union all
   select 'Student',
          id,
          user_id
     from student s 
) r
  ON u.user_id = r.user_id

答案 4 :(得分:0)

你写的UNION如何作为2个单独的SELECT语句

例如: SELECT * FROM User U JOIN Employee E ON E.User_Id = U.User_Id UNION SELECT * FROM User U JOIN student S ON S.User_Id = U.User_Id 我无法理解为什么你需要CASE声明它看起来多余。如果您想要所有用户并显示空值,请使用LEFT OUTER JOIN。

答案 5 :(得分:-1)

SELECT   OrderID, Quantity,  O.ProductID , ProductName,
CASE
WHEN Quantity > 3 THEN 'The quantity is More than 3'
WHEN Quantity = 3 THEN 'The quantity is Equal to  3'
ELSE 'The quantity is Less than 3'
END AS QuantityText

FROM            tb_OrderDetail O 
INNER JOIN      tb_Product     P   ON O.ProductID = P.ProductID