如何通过SELECT语句将两个不同表中的记录放入一列?

时间:2015-12-06 21:03:51

标签: mysql sql

因此,对于上下文,这就是我尝试排列信息的方式:如果事件是电影,请列出该类型。如果事件是播放 - 列出作者的姓名。第四列将被称为“流派/作者”。

电影是一张桌子,而Play是一张桌子。

我现在不知道如何列出相应的信息,而不会将查询结果分开或不返回任何内容。

这就是我的尝试:

    SELECT E.EventName, 
    V.VenueID, 
    E.Description, 
    (M.Genre AND P.Author) as 'Genre/Author' 
    FROM ( Event as E LEFT OUTER JOIN Venue as V
        ON E.VenueID = V.VenueID )
        LEFT OUTER JOIN
        Movie as M ON E.EventCode = M.EventCode
        LEFT OUTER JOIN
        Play as P ON E.EventCode = P.EventCode;

当该查询返回记录时,'类型/作者'专栏说" 0"下线。

    SELECT E.EventName, 
    V.VenueID, 
    E.Description, 
    M.Genre as Genre,
    P.Author as Author
    FROM ( Event as E LEFT OUTER JOIN Venue as V
        ON E.VenueID = V.VenueID )
        LEFT OUTER JOIN
        Movie as M ON E.EventCode = M.EventCode
        LEFT OUTER JOIN
        Play as P ON E.EventCode = P.EventCode;

上面的查询返回了正确的信息,但我希望将Genre和Author合并为一列。有小费吗?

1 个答案:

答案 0 :(得分:2)

您可以使用case根据事件名称选择所需的列。根据表中的数据更改条件。此外,对于所有其他事件名,此列为null

SELECT E.EventName, 
V.VenueID, 
E.Description, 
case when e.eventname = 'Movie' then M.Genre 
     when e.eventname 'Play' then P.Author 
end as Genre/Author
FROM Event as E 
LEFT OUTER JOIN Venue as V ON E.VenueID = V.VenueID 
LEFT OUTER JOIN Movie as M ON E.EventCode = M.EventCode
LEFT OUTER JOIN Play as P ON E.EventCode = P.EventCode