【问题标题】:derived table in subquery can't access main table子查询中的派生表无法访问主表
【发布时间】:2016-04-07 20:18:47
【问题描述】:

假设我想按 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 用Unknown column 'posts.id' in 'where clause' 大喊大叫。 我设法使它与加入、分组和 substring_index(group_concat(comments.id order by created_on DESC),",",2),但是cmet多的时候就很慢了。

还有更好的选择吗?

【问题讨论】:

  • id 列是否存在于posts 表中?
  • @RomanPerekhrest,是的,当然

标签: mysql sql subquery


【解决方案1】:

您可以在没有派生表的情况下重写查询:

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)

【讨论】:

  • 这行不通。 group_concat(id) 将占用所有行并且限制不相关。
  • select group_concat(id) from posts where id in (1,2,3) limit 1; 呈现:“1,2,3”
猜你喜欢
  • 2014-10-02
  • 2021-11-03
  • 2016-08-05
  • 1970-01-01
  • 1970-01-01
  • 2014-09-17
  • 2021-11-19
  • 1970-01-01
  • 2017-03-05
相关资源
最近更新 更多