[英]Join three tables with primary key in one and foreign key in other two tables
$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
我試圖從 3 個表中獲取上述字段但沒有得到它?
我想獲取date(tbl1),qty(tbl2),col_code(tbl2),col_code(tbl3),dept_code(tbl3)
.. 請幫助
可能沒有相同的鍵值。 請檢查表中的行數據。
您應該為列 col_code 使用別名以避免歧義(和相關查詢錯誤),因為這些列名存在於同一查詢中涉及的兩個不同表中,例如您可以添加別名 col_code_t2 和 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";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.