2012-03-15 71 views
0

我有一個包含兩個ID的表。我想從第一個表中選擇兩個id,並從兩個附加表中獲得兩行的結果集。也許我錯過了這裏顯而易見的,當我開始使用兩個id時,我如何抓取多行?MySQL中的兩個字段在一個表中從其他表中選擇兩個結果行?

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 

我已經縮短表中實際的列數簡單地說明一下,我希望能完成。首先,這看起來像是一個很好的數據設置?如果是,是否有一種簡單的方法來選擇數據?目前,我有一堆嵌套選擇正在失控並且似乎適得其反。無論如何,一如既往的任何幫助或指導表示讚賞。謝謝。

回答

1

上面的答案並不完全給我我期望實現的結果。最終,這是我結束了工作。謝謝您的幫助。

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 
0

也許會更好,這裏使用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 
0

根據還有什麼你必須在表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 

不要在過程中的生產代碼中使用*

0

像這樣的東西似乎會做你想要的,沒有任何嵌套的選擇。

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 = ?