0

我不确定解决这个问题的最佳方法,或者即使它是可能的。假设我有 4 个表、类别、文档、other_documents、more_documents 只有文档有一个其他人没有的类别。我正在使用 MySQL 和 PHP。我知道完全外连接不是 mysql 中的一个选项,必须使用左右连接来解决。

我可以获取所有文档并在其中加入与 id 匹配的类别,太棒了!

现在我有了上面的数据集,我还希望将 other_documents 和 more_documents “添加”到上述结果集的底部,并在类别不对齐的地方填充空值。

假设在 more_documents 表中有一个文档和 other_documents 表没有的唯一列。例如,phil 和 dave 将数据提交到文档和 other_documents 表中,而 jon 仅将数据提交到 more_documents 表中,因此结果将显示为:

ID - 标题 - 发布者 - 类别 - 唯一的 more_documents 列

1 - doc1 - 戴夫 - 全球 - 空

2 - doc2 - 菲尔 - 小时 - 空

3 - doc3 - 戴夫 - 操作 - 空

4 - doc4 - 戴夫 - 全球 - 空

5 - doc5 - 乔恩 - 全球 - 12345

6 - doc6 - 乔恩 - 小时 - 12345

4

1 回答 1

1

您想使用“驱动程序”子查询来构造查询:

select driver.Id, driver.Title, driver.publisher, c.category
from ((select id, categoryId, Title, publisher
       from documents
      ) union
      (select id, NULL, Title, publisher
       from more_documents
      ) union
      (select id, NULL, Title, publisher
       from other_documents
      )
     ) driver left outer join
     category c
     on driver.category_id = c.categoryId

请注意,uniondriver子查询中使用它,因为它会删除重复项。

您可能需要额外连接到文档表以获取仅在一个表中的字段。

于 2013-06-14T15:59:31.293 回答