SUM与mysql中的CASE语句

时间:2014-09-03 12:35:10

标签: mysql sql

我有以下Mysql查询

SELECT c.`id`
    ,c.`category_name`
    ,c.`category_type`
    ,c.bookmark_count
    ,f.category_id cat_id
    ,f.unfollow_at
    ,(
        CASE WHEN c.id = f.follower_category_id 
               THEN (
                        SELECT count(`user_bookmarks`.`id`)
                        FROM `user_bookmarks`
                        WHERE (`user_bookmarks`.`category_id` = cat_id)
                            AND ((`f`.`unfollow_at` > `user_bookmarks`.`created_at`) || (`f`.`unfollow_at` = '0000-00-00 00:00:00'))
                        ) 
               ELSE 0 END
        ) counter
    ,c.id
    ,f.follower_category_id follow_id
    ,c.user_id
FROM categories c
LEFT JOIN following_follower_categories f ON f.follower_category_id = c.id
WHERE c.user_id = 26
ORDER BY `category_name` ASC

以下是执行See Screen

后输出的内容

现在我只想数数。在这里,我的字段ID值 172 ,我有反 30,3,2 ,Bookmark_count 4 (我只需要包含一次) )

我接受id 172 的输出 30 + 3 + 2 + 4(bookmark_count只有一次)

我不知道该怎么做。

任何人都可以帮助我

非常感谢

1 个答案:

答案 0 :(得分:1)

以下可能是用于此目的的效率最低的查询,但我在查询中添加了一个封面,以暗示对结果进行分组。 (我删除了第二个c.id,我的例子可能有错误,因为我无法尝试。)

SELECT `id`,
       `category_name`,
       `category_type`,
       max(`bookmark_count`),
       `cat_id`,
       `unfollow_at`,
       sum(`counter`)+max(`bookmark_count`) counter,
       follow_id`, `user_id`
FROM
(SELECT c.`id`
    ,c.`category_name`
    ,c.`category_type`
    ,c.bookmark_count
    ,f.category_id cat_id
    ,f.unfollow_at
    ,(
        CASE WHEN c.id = f.follower_category_id
               THEN (
                        SELECT count(`user_bookmarks`.`id`)
                        FROM `user_bookmarks`
                        WHERE (`user_bookmarks`.`category_id` = cat_id)
                            AND ((`f`.`unfollow_at` > `user_bookmarks`.`created_at`) || (`f`.`unfollow_at` = '0000-00-00 00:00:00'))
                        )
               ELSE 0 END
        ) counter
    ,f.follower_category_id follow_id
    ,c.user_id
FROM categories c
LEFT JOIN following_follower_categories f ON f.follower_category_id = c.id
WHERE c.user_id = 26)
GROUP BY `id`, `category_name`, `category_type`, `cat_id`, `unfollow_at`, `follow_id`, `user_id`
ORDER BY `category_name` ASC