![](/img/trans.png)
[英]While joining 2 mysql tables how to get only the required related row in second table
[英]Im having trouble while joining two tables? How to write query while the second table has only one match first table
select
doc_id, doc_name_eng
from
mst_documents
where
doc_id in (161,248,249,250)
上面的查詢是我的 mst_documents 結果指定的四個文檔,下面的查詢是文檔上傳表,它只有一個記錄,只有一個doc_id 250的文檔
select
doc_id, document_status
from
bescom_appl_upload_doc
where
ack_no='EI000110259917'
當我嘗試左連接從 mst_documents 和 ack_no 獲取四個文檔時,一個文檔
select
doc.doc_id, doc.doc_name_eng, bes.document_status
from
mst_documents doc
left join
bescom_appl_upload_doc bes on bes.doc_id= doc.doc_id
where
doc.doc_id in (161,248,249,250)
and
ack_no ='EI000110259917' order by doc_id
但是我從第二張桌子上只得到了一條記錄。 幫助我從 mst_documents 中獲取四個文檔,如 where 條件中所述,並從第二個表中獲取一個文檔,如下圖鏈接所示
161“財產所有權/占用文件證明的副本。”
248“被許可人的權力制裁函副本。”
249、「估計草圖的副本」
250“估算和技術可行性報告的副本”。
當我再次加入另一張桌子時,我只得到一條記錄
select
doc.doc_id, doc.doc_name_eng, bes.document_status
from
application_ht_install app
inner join
bescom_appl_upload_doc bes on bes.ack_no = app.ack_no and app.ack_no='EI000110207048'
left join
mst_documents doc on doc.doc_id = bes.doc_id
where
doc.doc_id in (161,248,249,250)
and
status_code in ('INT','ACK') order by doc_id
您應該將 ack_no 條件移至 JOIN 條件,否則在進行連接后,您將從所有行中過濾出一行,從而導致只有 1 行並且不使用左連接功能。
select doc.doc_id, doc.doc_name_eng, bes.document_status from mst_documents doc
left join bescom_appl_upload_doc bes on bes.doc_id= doc.doc_id
left join application_ht_install app on bes.ack_no = app.ack_no and app.ack_no ='EI000110259917'
where doc.doc_id in (161,248,249,250) order by doc_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.