简体   繁体   中英

Join 4 tables in DB with Stored Procedure?

我的数据库中有一个表对其他3个表有3个FK我想在FK值=其他表中的PK值时选择此表中的数据+其他3个表中的数据

SELECT  *
FROM    t1
JOIN    t2
ON      t2.id = t1.t2_id
JOIN    t3
ON      t3.id = t1.t3_id
JOIN    t4
ON      t4.id = t1.t4_id
SELECT t1.Field1, t2.Field2, t3.Field3, t4.Field4
FROM Table t1
    INNER JOIN Table2 t2 ON t1.ID = t2.ID
    INNER JOIN Table3 t3 ON t1.ID = t3.ID
    INNER JOIN Table4 t4 ON t1.ID = t4.ID

If there aren't always matching rows in Tables 2 - 4, and you want those records return still then change the INNER JOINs to LEFT JOIN

SELECT * FROM ParentTable as pt
LEFT JOIN table1 as t1
ON pt.t1_ID = t1.ID
LEFT JOIN table2 as t2
ON pt.t2_ID= t2.ID
LEFT JOIN table3 as t3
ON pt.t3_ID= t3.ID

This will return a record even if there are not matches in table1,2 or 3. @Ada and @Q's will exclude those records.

SELECT * FROM TBL1 T1 RIGHT JOIN TBL2 T2 ON T1.id = T2.id RGIHT JOIN TBL3 T3 ON T3.id = T2.id

This will return all the records from Right table and matching records from Left 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