内联并依靠更新查询

时间:2019-02-14 09:58:19

标签: mysql sql

我有这个查询:

update posts 
set rank = (SELECT FIND_IN_SET( CONCAT(points, '_', comments_count, '_', created_at), 
    (SELECT GROUP_CONCAT( CONCAT(points, '_', comments_count, '_', created_at) ORDER BY points desc, comments_count desc, created_at desc ) 
FROM (select *, COUNT(comments.id) as comments_count from posts) as posts_rankings INNER JOIN comments ON comments.post_id = posts_rankings.id)))

我想获得每个帖子和下一个订单的评论数,并以此计数。我该怎么做?现在我得到了错误:unknown column comments.id in field list

我的表格结构:

enter image description here

enter image description here

我根据pointscomments_countcreated_at的顺序计算职位等级。

1 个答案:

答案 0 :(得分:2)

您不能在同一子查询中选择分组值和非分组值。您需要两个子查询,一个子查询执行所有帖子的GROUP_CONCAT(),另一个子查询获取每个特定帖子的值并获得其在串联列表中的排名。

UPDATE posts AS p
JOIN (
    SELECT p1.id, FIND_IN_SET(CONCAT_WS('_', p1.points, p1.comments_count, p1.created_at), all_post_counts) AS rank
    FROM (
        SELECT p.id, p.created_at, p.points, IFNULL(COUNT(c.id), 0) AS comments_count
        FROM posts AS p
        LEFT JOIN comments AS c ON c.post_id = p.id
        GROUP BY p.id
    ) AS p1
    CROSS JOIN (
        SELECT GROUP_CONCAT(CONCAT_WS('_', p1.points, p1.comments_count, p1.created_at) ORDER BY points desc, comments_count desc, created_at desc) AS all_post_counts
        FROM (
            SELECT p.id, p.created_at, p.points, IFNULL(COUNT(c.id), 0) AS comments_count
            FROM posts AS p
            LEFT JOIN comments AS c ON c.post_id = p.id
            GROUP BY p.id
        ) AS p1
    ) AS p3
) AS p4
ON p.id = p4.id
SET p.rank = p4.rank

确保将group_concat_max_len设置得足够大,以将所有结果保存在该子查询中。