MySQL在子查询错误中引用外部表别名

时间:2014-01-09 03:47:33

标签: mysql

  select c.*
    from posts p
    join comments c on (p.id=c.post_id) 
        and c.status = 'A' 
        and c.id >= (select MIN(id) from (select id from comments where post_id=p.id order by id DESC LIMIT 7) as c2)
    where p.comments_count > 0 AND p.id IN (247,245,244,243,242,241)

在上面的sql查询中,我得到了这个mysql错误未知列'p.id'在'where子句'中,它似乎在子查询p.id中无法被引用。反正我是否可以获得此子查询中引用的posts表id?

2 个答案:

答案 0 :(得分:0)

您只能访问1级深层次的外部查询。所以尝试在中间查询过滤器的位置:

SELECT MIN(id)
FROM (
    SELECT id, post_id 
    FROM   comments 
    ORDER  BY id DESC 
    LIMIT  7
)
WHERE post_id = p.id 

答案 1 :(得分:0)

我认为您正在尝试为每个帖子获取最新的7条评论。你能试试吗?你可以在这里测试http://www.sqlfiddle.com/#!2/a222e/3/0

第一次尝试

我在SQL下面尝试过。

SELECT *
FROM comments t1
WHERE post_id IN (247,254,244,243,242,241)
AND id IN (
    SELECT id
    FROM comments
    WHERE t1.id = id
    LIMIT 7
);

但是我收到错误"这个版本的MySQL还没有支持' LIMIT& IN / ALL / ANY / SOME子查询"

另一种方法

所以,我尝试自我加入评论以生成序列号。

SELECT id
FROM (
    SELECT t1.id, COUNT(*) AS cnt
    FROM comments t1 INNER JOIN comments t2
      ON t1.post_id = t2.post_id
    WHERE t1.id <= t2.id
      AND t1.post_id IN (247,254,244,243,242,241)
      AND t2.post_id IN (247,254,244,243,242,241)
    GROUP BY t1.id
) x
WHERE cnt <= 7;

内部子查询使用自我加入并生成cnt列,该列具有帖子的每个评论ID的顺序值。

但前面的查询仅提取评论的id

最后获取评论表的所有列,应执行以下查询。

SELECT *
FROM comments c INNER JOIN (
    SELECT id
    FROM (
        SELECT t1.id, COUNT(*) AS cnt
        FROM comments t1 INNER JOIN comments t2
          ON t1.post_id = t2.post_id
        WHERE t1.id <= t2.id
          AND t1.post_id IN (247,254,244,243,242,241)
          AND t2.post_id IN (247,254,244,243,242,241)
        GROUP BY t1.id
    ) x
    WHERE cnt <= 7
) t USING (id);

使用用户变量

实际上你还有机会使用MySQL user variable。我没有提到这个有趣的MySQL功能,因为我不确定我是否理解你的问题。

SELECT * 
FROM (
    SELECT post_id, id,
        IF (@pid = post_id, @cnt := @cnt + 1, @cnt := 1) AS cnt,
        @pid := post_id
    FROM comments, (SELECT @pid := 0, @cnt := 0) tmp
    WHERE post_id IN (247,254,244,243,242,241)
    ORDER BY post_id, id DESC
) x
WHERE cnt <= 7;

与旧的连接版本相比,前置SQL看起来更简单(意味着更好的性能)。但未在大数据集上进行测试。