如何选择与单个表相关的多对多

时间:2016-05-03 15:04:46

标签: sql sql-server many-to-many select-query

我目前正在使用数据库,但我遇到了一个选择查询。 但是,我不是数据库专家。 查询应该从具有多对多关系的表中返回数据。

这是我的表格图表,它将显示我的问题的概念

enter image description here

选择查询应该查看三个列,即VidTbl.Name,ActorTbl.Name和SubTitelTbl.name。

所以,我已经在互联网上阅读和搜索,并且我已经尝试了

首先尝试

SELECT  
        VidTbl.NAME AS Video_Titel_Name,
        ActorTbl.NAME AS Actor_Name

FROM    ActorInVid 

INNER JOIN VidTbl

ON VidTbl.Id = ActorInVid.FKVidId 

INNER JOIN ActorTbl

ON ActorTbl.Id = ActorInVid.FKActorId



UNION all

SELECT 
        VidTbl.NAME AS Video_Titel_Name,
        SubTitelTbl.NAME AS SubTitel_Langu

FROM SubTitelInVid

INNER JOIN VidTbl

ON VidTbl.Id = SubTitelInVid.FKVidId

INNER JOIN SubTitelTbl 

ON SubTitelTbl.Id = SubTitelInVid.FKSTId

结果我得到了,这是错误的

enter image description here

然后我尝试了另一种方法来解决这个问题,但我又遇到了另一个错误

第二次尝试

    SELECT Temp1.* 
From  (SELECT    VidTbl.Id        AS Video_Id,
                 VidTbl.NAME      AS Video_Titel_Name,
                 ActorTbl.NAME    AS Actor_Name

       FROM      ActorInVid  
       INNER JOIN VidTbl
               ON VidTbl.Id = ActorInVid.FKVidId 
       INNER JOIN ActorTbl
               ON ActorTbl.Id  = ActorInVid.FKActorId) AS  Temp1

SELECT Temp2.*
FROM  (SELECT VidTbl.Id           AS Video_Id,
              SubTitelTbl.NAME    AS SubTitel_Langu 
      FROM SubTitelInVid
INNER JOIN VidTbl
        ON VidTbl.Id      = SubTitelInVid.FKVidId
INNER JOIN SubTitelTbl 
        ON SubTitelTbl.Id = SubTitelInVid.FKSTId) AS Temp2


SELECT * 
FROM   VidTbl
INNER JOIN Temp1 
        on Temp1.Video_Id = VidTbl.Id
INNER JOIN Temp2
        on Temp2.Video_Id = VidTbl.Id

错误,我在最后一次选择错误

非常感谢你的帮助 我希望我的问题清楚而有用 再次感谢。

2 个答案:

答案 0 :(得分:1)

你很亲密。这应该有用......

SELECT 
VidTbl.Name, 
ActorTbl.Name, 
SubTitelTbl.name
FROM VidTbl
INNER JOIN ActorInVid ON VidTbl.Id = ActorInVid.FKVidId 
INNER JOIN ActorTbl ON ActorTbl.Id = ActorInVid.FKActorId
INNER JOIN SubTitelInVid ON VidTbl.Id = SubTitelInVid.FKVidId
INNER JOIN SubTitelTbl ON SubTitelTbl.Id = SubTitelInVid.FKSTId

答案 1 :(得分:0)

SELECT DISTINCT vt.Name, at.Name, st.Name
FROM VidTbl vt
JOIN ActionInVid aiv ON aiv.VidId = vt.Id
JOIN SubtitleInVid siv ON siv.VidId = vt.Id
JOIN ActorTbl at ON at.Id = aiv.ActorId
JOIN SubTitleTbl st ON st.Id = siv.STId