有两个表,q_entries
(80 条记录)和相关的q_entries_comments
(37 条记录)。
当我加入时:
select q_entries.*,q_entries_comments.comment
from q_entries
left join q_entries_comments
on q_entries_comments.entry_id=q_entries.id
我得到 109 条记录。
现在,我想将结果限制为仅 10 个条目,首先我这样做:
select q_entries.*,q_entries_comments.comment
from q_entries
left join q_entries_comments
on q_entries_comments.entry_id=q_entries.id
limit 0,10
但这不是我想要的 - 在结果集中有一个 id=1 的重复条目,并且该“条目”附加了 10 条注释。
我想要的是获得 10 个不同的条目,以及每个条目的评论数量,所以我这样做:
select q_entries.*,q_entries_comments.comment
from (select * from q_entries limit 0,10) as q_entries
left join q_entries_comments
on q_entries_comments.entry_id=q_entries.id
现在我得到了我想要的,即 37 条记录(前 10 个“条目”有很多评论),但只有 10 个前“条目”。
当我向相关表添加 where
语句时,就会出现问题,如下所示:
select q_entries.*,q_entries_comments.comment
from (select * from q_entries limit 0,10) as q_entries
left join q_entries_comments
on q_entries_comments.entry_id=q_entries.id
where q_entries_comments.comment like '%b%'
它显然向我显示的“条目”太少,因为它仅在前 10 个“条目”附带的注释中搜索“%b%”。我真正想要的是始终获得 10 个“条目”以及附加的所有评论。
如何做到这一点?
最佳答案
您可以在第二个内部查询中使用 WHERE 子句,如下所示:
select q_entries.*,q_entries_comments.comment
from (select * from q_entries limit 0,10) as q_entries
left join (select * from q_entries_comments where q_entries_comments.comment like '%b%') as q_entries_comments
on q_entries_comments.entry_id=q_entries.id
关于mysql - 对连接表进行带有连接和 'where' 语句的子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27145874/