根据给定的ID从不同的表中获取值

时间:2015-04-10 15:40:20

标签: sql postgresql null left-join union-all

我试图通过在PostgreSQL中使用StaffID检查不同的CASE来获取不同的名称。

SELECT StaffID,
       CASE WHEN StaffID IS NULL THEN 
          (SELECT C.Name FROM Customer as C, Ticket as T, TicketUpdate as TU
           WHERE TU.TicketID = 13 
           AND TU.TicketID = T.TicketID 
           AND T.CustomerID = C.CustomerID)

        WHEN StaffID IS NOT NULL THEN 
           (SELECT S.Name FROM Staff AS S, TicketUpdate as TU
           WHERE TU.TicketID = 13 
           AND TU.StaffID = S.StaffID offset)
        END
FROM ticketupdate
WHERE ticketid = 13;    

如果我没有将输出限制为1,则会出现错误:

ERROR:  more than one row returned by a subquery used as an expression

但是如果我在查询结尾添加LIMIT 1,它只需要所有StaffID的第一个值

enter image description here

实际上它看起来像这样:

enter image description here

至于我的理解,它需要不同的ID,但不会使用相关的名称。我在这件事上输了。

1 个答案:

答案 0 :(得分:1)

查询(据我所知)并非易事,在这里很容易丢失。但是,由于多种原因,你失败了 填写缺失信息的有根据的猜测,它可能看起来像这样:

SELECT staffid, s.name
FROM   ticketupdate tu
JOIN   staff        s USING (staffid)
WHERE  tu.ticketid = 13

UNION ALL
SELECT tu.staffid, c.name
FROM   ticketupdate  tu
LEFT   JOIN ticket   t USING (ticketid)
LEFT   JOIN customer c ON c.customerid = t.customerid
WHERE  tu.ticketid = 13
AND    tu.staffid IS NULL;

假设staffidstaff的主键,并且您在ticketupdate中有一个外键约束,则会检索一个 {{1} } name每行staff staffid。{/ p>

否则,从NOT NULL检索任意数量的名称,以在结果中生成1-n行。只要找到customerLEFT JOIN就会保证至少有一行。