MySQL在一个表中的两个字段中从另外的表中选择两个结果行?

时间:2012-03-15 21:19:28

标签: mysql

我有一个包含两个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

我缩短了表中实际列的数量,以简单说明我希望完成的内容。首先,这看起来像是一个很好的数据设置吗?如果是,是否有一种简单的方法来选择数据?目前,我有一堆嵌套的选择失控,似乎适得其反。无论如何,总是任何帮助或指导表示赞赏。感谢。

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:0)

根据table1中的其他内容,在同一行中包含两个单独的文档ID可能不是一个好主意。但你可以尝试的是一个union子查询:

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

当然,不要在生产代码中使用*

答案 3 :(得分: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 = ?