简体   繁体   中英

How to join 2 tables with a common column in another 3rd table?

I want to join table people with table video but they don't have direct common column between them but both tables have common column with table village so help me out to join table people with table video .

PEOPLE

id                 village_id
 1                 smg

VIDEO

id               village_id
 1                 smg  

VILLAGE

id               name
smg                hdd

I have tried the following code but its not working:

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

If the table structure you provided is correct, then you do have a link between videos and people. You have village_id...

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

IF you don't want any repeated values, then you could do a SELECT DISTINCT like this

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

Could you provide more details on what exactly you are wanting?

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;

I am assuming you want to do a triple JOIN. I first joined people and village into a table and named it as T and joined T with video table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM