mysql - 从没有所有组合的多个表中获取相关行

mysql - fetch related rows from multiple tables without all combinations

假设我有一个主要的 table record,它有 2 个相关的 tables fieldscomments.

CREATE TABLE record (id int primary key, name varchar(20))
CREATE TABLE fields (record_id int, name varchar(20), val int)
CREATE TABLE comments (record_id int, who varchar(20), comment text)

我想要 运行 一个获取一组记录并获取该记录的所有相关字段并获取与该记录相关的所有评论的查询。

如果我使用左连接来确保我得到记录,我会使用:

select * from record
     left join fields on (fields.record_id = record.id)
     left join comments on (comments.record_id = record.id)
     order by record.id

问题是,我为每条记录取回 n * m 行,其中 n 是字段数,m 是评论数。我想取回 n + m 行(有意义的是,返回评论时字段列全部为空,返回字段时评论列全部为空)。除了插入虚拟评论和虚拟字段以加入之外,有没有办法使这项工作正常进行?我非常希望不必为每条记录执行额外的查询。

我想这不是 mysql 特定的,但这就是我在我的应用程序中使用的。

I get back n * m rows for each record, where n is the number of fields, and m is the number of comments. I want to get back n + m rows

    SELECT * 
    FROM record
    LEFT JOIN fields ON (fields.record_id = record.id) /* maybe INNER JOIN ? */
    LEFT JOIN comments ON (1=0)
UNION ALL
    SELECT * 
    FROM record
    LEFT JOIN fields ON (1=0)
    LEFT JOIN comments ON (comments.record_id = record.id) /* maybe INNER JOIN ? */
-- ORDER BY record.id

I want to get back n + m rows (what makes sense is that the fields columns are all null while returning the comments, and the comments columns are all null while returning the fields)

一个选项在子查询中使用 union all,然后是 left join:

select *
from record r
left join (
    select record_id, name, val, null who, null comment from fields
    union all record_id, select null, null, who, comment from comments
) x on x.record_id = r.record_id

虽然这是一个奇怪的结果集。