如何从所有表中返回所有记录?

时间:2014-05-19 08:22:00

标签: sql database join

对于学校作业,我必须编写一个查询,我需要加入数据库中的所有表。 该数据库如下所示:

Screenshot

因此查询需要连接所有表并显示所有记录。 我正在尝试这样做,但过去几天它没有用。 任何人都可以帮助我吗?

我尝试了什么:

SELECT *
FROM gebruiker G,
    gebruiker G2 gebruikertype GT,
    aankoop A,
    trackaankoop TA,
    track T,
    genre GE
WHERE G.idGebruikertype = GT.idGebruikertype
    AND G.idGebruiker = A.idGebruiker
    AND A.idAankoop = TA.idAankoop
    AND TA.idTrack = T.idTrack
    AND T.idGebruiker = G2.idGebruiker
    AND T.idGenre = GE.idGenre.

2 个答案:

答案 0 :(得分:0)

如果必须使用JOIN显示所有表的所有行,则需要FULL JOIN来显示记录。

SELECT *
FROM gebruiker G 
    FULL JOIN gebruikertype GT ON G.idGebruikertype = GT.idGebruikertype
    FULL JOIN aankoop A ON G.idGebruiker = A.idGebruiker
    FULL JOIN trackaankoop TA ON A.idAankoop = TA.idAankoop
    FULL JOIN track T ON TA.idTrack = T.idTrack
    FULL JOIN gebruiker G2 ON T.idGebruiker = G2.idGebruiker
    FULL JOIN genre GE ON T.idGenre = GE.idGenre

使用WHERE子句重新创建的JOIN类型是INNER JOIN,其中只显示所有表中包含通讯记录的记录。

答案 1 :(得分:0)

假设Gebruiker是主表,您可以使用以下内容加入

 SELECT G.*, R.*, GT.*, T.*, TG.*, A.*, C.*, TA.*
   FROM gebruiker AS G
        JOIN gebruikertype as GT ON GT.idGebruikerType = G.idGebruikerType
        JOIN review AS R ON R.idGebruiker = G.idGebruiker
        JOIN track AS T ON T.idGebruiker = G.idGebruiker
             JOIN genre as TG ON TG.idGenre = T.idGenre
        JOIN aankoop AS A ON A.idGebruiker = G.idGebruiker
             JOIN creditaankoop AS C ON C.idAankoop = A.idAankoop
             JOIN trackaankoop as TA ON TA.idAankoop = A.idAankoop

SELECT G.*, R.*, GT.*, T.*, TG.*, A.*, C.*, TA.*可以替换为SELECT *

评论可以加入Gebruiker表:

 SELECT G.*, R.*
   FROM gebruiker AS G
        JOIN review AS R ON R.idGebruiker = G.idGebruiker

或跟踪表:

 SELECT T.*, R.*
   FROM track AS T
        JOIN review AS R ON R.idTrack = T.idTrack

同样,TrackAankoop表可以加入Aankoop表:

 SELECT G.*, A.*, TA.*
   FROM gebruiker AS G
        JOIN aankoop AS A ON A.idGebruiker = G.idGebruiker
             JOIN trackaankoop AS TA ON TA.idAankoop = A.idAankoop

或Track表;

 SELECT T.*, TA.*
   FROM track AS T
        JOIN trackaankoop AS TA ON TA.idTrack = T.idTrack