简体   繁体   中英

Join three tables with primary key in one and foreign key in other two tables

enter image description here

$query="SELECT i.trans_date, f.col_code,f.trans_qty ,t.dept_code 
        FROM table1 AS i 
        LEFT JOIN table2 AS f 
        ON f.trans_no=i.trans_no 
        LEFT JOIN table3 AS t 
        ON t.trans_no=i.trans_no";

trans_no --> Primary key in table 1
trans_no --> Foreign key in table 2,3

I am trying to fetch the above fields from the 3 tables but not getting it?

I wanna fetch date(tbl1),qty(tbl2),col_code(tbl2),col_code(tbl3),dept_code(tbl3) .. Plz Help

Probably doesn't have the same key values. Please check the row data in your tables.

You should use alias for columns col_code for avoid ambiguity ( and related query error ) due the fact these column name is present in tow different tables involved in the same query eg you could add the alias col_code_t2 and cold_code_t3

query="Select i.trans_date
  , f.col_code col_code_t2

  , f.trans_qty 
  , t.col_code cold_code_t3
  , t.dept_code 
from table1 AS i 
LEFT JOIN table2 AS f ON f.trans_no=i.trans_no 
LEFT JOIN table3 AS t ON t.trans_no=i.trans_no";

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