mysql - 对连接表进行带有连接和 'where' 语句的子查询

标签 mysql join subquery

有两个表,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/

相关文章:

mysql - 如何选择表名为 : "group"? 的表

mySQL 1 个语句中的多个联接仅显示属性标题

mysql - 如何让 Round() 的第二个参数与列一起使用?

mysql - 选择每个人的最后一条记录

mysql - 为未使用的槽生成空行

C# 查询 MySql 数据库不返回所有列

mysql - SQL:如何从两个表中获取关系数据? (使用 JOIN ?)

MYSQL:操作数应包含 1 列

php - 如果 MySQL 同时获得相同的 UPDATE 查询会发生什么?

C#/LINQ(?) - 加入两个数据表(没有 SQL!)