2014-09-03 131 views
1

我有以下MySQL查詢SUM與CASE語句在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 

,這裏是什麼輸出我得到後execuation See Screen

現在我只想計數。這裏我有具有值字段id反對我有計數器30,3,2和BOOKMARK_COUNT是(我需要包括僅一次)

,我接受輸出ID 是30 + 3 + 2 + 4(bookmark_count只有一次)

我不知道如何做到這一點。

任何人都可以幫我

非常感謝

+0

你想返回3行中的id = 172(全部具有BOOKMARK_COUNT = 4和反= 39),還是隻有一行? – yalpertem 2014-09-03 12:57:32

回答

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 
+0

不存在反碼字段 – kamalpreet 2014-09-04 02:41:06