![](/img/trans.png)
[英]MySQL select multiple row on table 2 with two differents Id from table 1 result in one row as two differents fields
[英]MySQL two fields in one table to SELECT two result rows from additional tables?
我有一個包含兩個ID的表。 我想從第一個表中選擇兩個ID,並從另外兩個表中獲得兩行的結果集。 也許我在這里沒有明顯的地方,當我從兩個id開始時如何抓取多行?
Table 1 = Intial SELECT
id | document1_id | document2_id
SELECT FROM table1 document_id1, document_id2
Table 2
document_id | document_title | document_description
Table 3
document_id | document_filename
我想獲得兩個匹配document_id1和document_id2的結果行。 這是我開始嵌套選擇的地方。 這沒有起作用。 我可以在這里做兩個聯接嗎?
我想要達到的結果是:
1 row from table 1
table1_id, document1_id, document2_id
2 rows from table 2
document_title, document_description that matches document1_id AND
document_title, document_description that matches document2_id
2 rows from table 3
document_filename that matches document1_id AND
document_filename that matches document2_id
我已經縮短了表中的實際列數,只是為了說明我希望完成的工作。 首先,這看起來像是對數據的良好設置嗎? 如果是,是否有一種簡單的方法來選擇數據? 目前,我有一堆嵌套選擇,這些選擇已失去控制,並且似乎適得其反。 無論如何,一如既往的任何幫助或指導都值得贊賞。 謝謝。
上面的答案並沒有完全給我我想要達到的結果。 最終,這就是我最終獲得的成功。 謝謝您的幫助。
SELECT
t1.document1_id, t1.document2_id,
t21.document_title as t21_title, t21.document_description as t21_description,
t22.document_title as t22_title, t22.document_description as t22_description,
t31.document_filename as t31_filename,
t32.document_filename as t32_filename
FROM
Table1 t1
INNER JOIN Table2 t21
ON t21.document_id = t1.document1_id
INNER JOIN Table2 t22
ON t22.document_id = t1.document2_id
INNER JOIN Table3 t31
ON t31.document_id = t1.document1_id
INNER JOIN Table3 t32
ON t32.document_id = t1.document2_id
也許在這里使用union會更好:
select t1.id, t1.document1_id as doc_id, t2.document_title, t2.document_description, t3.document_filename
FROM table1 t1
LEFT JOIN table2 t2 ON t2.document_id=t1.document1_id
LEFT JOIN table2 t3 ON t3.document_id=t1.document1_id
UNION
select t1.id, t1.document2_id as doc_id, t2.document_title, t2.document_description, t3.document_filename
FROM table1 t1
LEFT JOIN table2 t2 ON t2.document_id=t1.document2_id
LEFT JOIN table2 t3 ON t3.document_id=t1.document2_id
根據表1中的其他內容,在同一行中具有兩個單獨的文檔ID可能不是一個好主意。 但是您可以嘗試的是並集子查詢:
SELECT table2.*, table3.*
FROM (
SELECT document_id1 AS document_id
FROM table1
WHERE id = ?
UNION ALL
SELECT document_id2 AS document_id
FROM table1
WHERE id = ?
) table1a
INNER JOIN table2 ON table1a.document_id = table2.document_id
INNER JOIN table3 on table1a.document_id = table3.document_id
當然,請勿在生產代碼中使用*
。
像這樣的事情似乎可以完成您想要的任何嵌套選擇。
SELECT Table1.id, Table1.document1_id, Table1.document2_id,
Table2.document_title, Table2.document_description,
Table3.document_filename
FROM Table1 JOIN Table2 ON Table2.document_id = Table1.document1_id OR
Table2.document_id = Table1.document2_id
JOIN Table3 ON Table3.document_id = Table2.document_id
WHERE Table1.id = ?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.