简体   繁体   English

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

[英]mysql - fetch related rows from multiple tables without all combinations

Let's say I have a primary table record , and it has 2 related tables fields and comments .假设我有一个主表record ,它有 2 个相关的表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)

I would like to run one query that fetches a set of records AND fetches all the related fields for that record, AND fetches all the comments related to that record.我想运行一个查询来获取一组记录并获取该记录的所有相关字段,并获取与该记录相关的所有评论。

If I do left joins to ensure I get the records, I would use:如果我做左连接以确保获得记录,我会使用:

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

The problem is, I get back n * m rows for each record, where n is the number of fields, and m is the number of comments.问题是,我为每条记录返回 n * m 行,其中 n 是字段数,m 是评论数。 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).我想取回 n + m 行(有意义的是,返回评论时字段列全为空,返回字段时注释列全为空)。 Is there a way to make this work aside from inserting a dummy comment and dummy field to join with?除了插入一个虚拟评论和虚拟字段来加入之外,有没有办法让这项工作? I would very much prefer not to have to perform an extra query for each record.我非常希望不必为每条记录执行额外的查询。

I suppose this is not mysql specific, but that's what I'm using for my application.我想这不是特定于 mysql 的,但这就是我在我的应用程序中使用的。

I get back n * m rows for each record, where n is the number of fields, and m is the number of comments.我为每条记录返回 n * m 行,其中 n 是字段数,m 是评论数。 I want to get back n + m rows我想取回 n + m 行

    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)我想取回 n + m 行(有意义的是,返回评论时字段列全为空,返回字段时注释列全为空)

One option uses union all in a subquery, then a left join :一种选择在子查询中使用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

That's a weird resultset though.不过,这是一个奇怪的结果集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM