Mysql 子查询中的派生表无法访问主表

Mysql 子查询中的派生表无法访问主表,mysql,sql,subquery,Mysql,Sql,Subquery,假设我想按id加载帖子,每个帖子有3个最后的评论id。 本机编写了以下查询: select id, (select group_concat(id) from (select id from comments where post_id = posts.id order by created_on desc limit 3) ids) from posts where id in (1,2,3) 但是,mysql在“where子句”中使用未知列“posts.id”进行叫喊。 我设法

假设我想按id加载帖子,每个帖子有3个最后的评论id。 本机编写了以下查询:

select id, (select group_concat(id) from 
  (select id from comments where post_id = posts.id
   order by created_on desc limit 3) ids)
from posts where id in (1,2,3)
但是,mysql在“where子句”中使用未知列“posts.id”进行叫喊。 我设法通过加入、分组和 子字符串_indexgroup _concatcomments.id按在DESC、、2上创建的顺序排列,但当有许多注释时速度非常慢


有更好的选择吗?

您可以在不使用派生表的情况下重写查询:

select id, (select group_concat(id) 
    from comments where post_id = posts.id
    order by created_on desc limit 3)
from posts where id in (1,2,3)

您可以在不使用派生表的情况下重写查询:

select id, (select group_concat(id) 
    from comments where post_id = posts.id
    order by created_on desc limit 3)
from posts where id in (1,2,3)

posts表中是否存在列id?@RomanPerekhrest,是的,当然是。posts表中是否存在列id?@RomanPerekhrest,是的,当然是。它将不起作用。group_concatid将占据所有行,限制将不相关。从id位于1,2,3 limit 1的帖子中选择group_concatid;渲染:1,2,3它不起作用。group_concatid将占据所有行,限制将不相关。从id位于1,2,3 limit 1的帖子中选择group_concatid;渲染:1,2,3