简体   繁体   中英

Joining 4 Tables in a stored procedure

I have four tables and I need to get data from all of them through a stored procedure. Table 1 is the main table and is laid out like this

ID  REF1  REF2  Data1
 1   01    11    abc
 2   01    22    def
 3   01    33    ghi

Table 2 looks like this

ID  ref2ID  Data2
 1    11     a
 2    99     x

Table 3

ID  ref3ID  Data3
 1    22     b

Table 4

ID  ref4ID  Data4
 1    33     c

How would I get the data from all four tables based on the 'REF2' column.

I tried something like this, but I don't get the right data. I need to bring all the records on Data1, Data2, Data3 and Data4 column

Select Table1.Data1,
       Table2.Data2,
       Table3.Data3,
       Table4.Data4,
From   Table1 INNER JOIN
       Table2 ON Table1.REF2 = Table2.Ref2ID INNER JOIN 
       Table3 ON Table1.REF2 = Table3.Ref3ID INNER JOIN
       Table4 ON Table1.REF2 = Table4.Ref4ID
WHERE  REF1 = "01"

What am I doing wrong? please help

Try with LEFT JOIN s in this case, amd also use single quotes for strings:

SELECT Table1.Data1,
       Table2.Data2,
       Table3.Data3,
       Table4.Data4
FROM   Table1 
LEFT JOIN Table2 
    ON Table1.REF2 = Table2.Ref2ID 
LEFT JOIN Table3 
    ON Table1.REF2 = Table3.Ref3ID 
LEFT JOIN Table4 
    ON Table1.REF2 = Table4.Ref4ID
WHERE  REF1 = '01'

Here is a sqlfiddle with a demo for you to try.

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