如何将2个表与另一个3rd表中的公共列联接?

时间:2018-07-05 23:19:17

标签: mysql sql database join

我想将表 people 与表 video 联接在一起,但他们之间没有直接的公共列,但两个表的表与 village < / strong>,请帮助我加入表和表视频

id                 village_id
 1                 smg

视频

id               village_id
 1                 smg  

村庄

id               name
smg                hdd

我尝试了以下代码,但无法正常工作:

SELECT people.id, video.id
FROM people
JOIN village ON people.village_id = village.id
JOIN video ON video.village_id = village.id

2 个答案:

答案 0 :(得分:0)

如果您提供的表格结构正确,那么您在视频和人物之间确实存在链接。您有village_id ...

SELECT p.id , vid.id 
FROM people  as p 
INNER JOIN video as vid 
    ON vid.village_id = p.village_id 

如果您不希望有任何重复的值,则可以像这样SELECT DISTINCT

SELECT DISTINCT p.id , vid.id 
FROM people  as p 
INNER JOIN video as vid 
    ON vid.village_id = p.village_id 

您能否提供有关您到底想要什么的更多详细信息?

答案 1 :(得分:0)

SELECT  * FROM

(SELECT people.village_id AS pv_id, village.id AS v_id FROM
people JOIN village ON people.village_id = village.id) AS T

JOIN video ON video.village_id = T.v_id;

我假设您要进行三次JOIN。我首先将人和村庄合并到一个表中,并将其命名为T,然后将T与视频表合并。