将Count与Group Concat一起使用

时间:2014-11-10 18:58:47

标签: mysql sql database count

Fiddle Example

我有一个页面列出了表格vote_option中的多个民意调查及其所有投票选项。我使用表user_vote来存储用户'投票记录。我想从该表中检索每个投票中每个投票选项的投票结果。任何人都可以告诉我如何将GROUP_CONCATSELECT COUNT(*) FROM user_vote GROUP BY product_id一起使用,以便结果如下:

Poll_TITLE   VOTE_OPTION                     IMG                VOTE_COUNT <---how to get this column 
Title A      Product A,Product B,Product C   imgA,imgB,imgC     2,0,1  
Title B      Product A,Product B,Product D   imgA,imgB,imgD     0,1,0
Title C      Product D,Product E             imgD,imgE          1,0  

表架构:

CREATE TABLE poll
    (`poll_id` int,`title`varchar(30))
;

INSERT INTO poll
    (`poll_id`,`title`)
VALUES
    (1,'Title A'),
    (2,'Title B'),
    (3,'Title C')

;

CREATE TABLE product
    (`product_id` int,`product_name` varchar(30),`img`varchar(30))
;

INSERT INTO product
    (`product_id`,`product_name`,`img`)
VALUES
    (1,'Product A','imgA'),
    (2,'Product B','imgB'),
    (3,'Product C','imgC'),
    (4,'Product D','imgD'),
    (5,'Product E','imgE')
;

CREATE TABLE vote_option
    (`poll_id` int,`product_id` int)
;

INSERT INTO vote_option
    (`poll_id`,`product_id`)
VALUES
    (1,1),
    (1,2),
    (1,3),
    (2,1),
    (2,2),
    (2,4),
    (2,2),
    (3,4),
    (3,5)

;

CREATE TABLE user_vote
    (`poll_id` int,`product_id` int,`user_id` int)
;

INSERT INTO user_vote
    (`poll_id`,`product_id`,`user_id`)
VALUES
    (1,1,1),
    (1,1,2),
    (1,3,2),
    (2,2,1),
    (3,4,1)
;

CREATE TABLE user
    (`user_id` int,`user_name` varchar (30))
;

INSERT INTO user
    (`user_id`,`user_name`)
VALUES
    (1,'Tom'),
    (2,'Sally')
;

1 个答案:

答案 0 :(得分:2)

您需要首先在更精细的级别聚合数据以获取计数,然后在轮询级别重新聚合:

SELECT title,
       GROUP_CONCAT(product_name) as products,
       GROUP_CONCAT(img) as imgs,
       GROUP_CONCAT(cnt) as cnt
FROM (SELECT p.poll_id, p.title, pr.product_name, img, count(distinct uv.user_id) as cnt
      FROM vote_option v INNER JOIN
           poll p
           ON p.poll_id = v.poll_id INNER JOIN
           product pr
           ON pr.product_id = v.product_id LEFT JOIN
           user_vote uv
           ON uv.product_id = v.product_id AND
              uv.poll_id = v.poll_id LEFT JOIN
           user u
           ON uv.user_id = u.user_id
      GROUP BY p.poll_id, p.title, pr.product_name, img
     ) p
GROUP BY title
LIMIT 0, 25;

请注意,您可以使用以下内容将数据放入单个列表中:

SELECT title,
       GROUP_CONCAT(product_name, ',', img, ',', cnt separator '; ')

通过在order by中使用group_concat()子句,您可以在列表中拥有最高的投票获取者。