1

我希望在每行调查中列出总视图:

CREATE TABLE IF NOT EXISTS `survey` (
      `id` int(6) unsigned NOT NULL,
      `title` varchar(200) NOT NULL,
      `url` varchar(200) NOT NULL,
      PRIMARY KEY (`id`)
    ) DEFAULT CHARSET=utf8;
    INSERT INTO `survey` (`id`, `title`, `url`) VALUES
      ('1', 'ants on the hill', 'https://mypoll.io/xyz'),
      ('2', 'crocs in the swamp', 'https://mypoll.io/xyz'),
      ('3', 'baboon on the loose', 'https://mypoll.io/another-term.');


      CREATE TABLE IF NOT EXISTS `views` (
      `id` int(6) unsigned NOT NULL,
      `poll_id` int(6) unsigned NOT NULL,
      `count` int(6) NOT NULL,
       PRIMARY KEY (`id`),
       FOREIGN KEY (poll_id) REFERENCES survey(id)
    ) DEFAULT CHARSET=utf8;
    INSERT INTO `views` (`id`, `poll_id`, `count`) VALUES
      ('1', 1, 1),
      ('2', 2, 1),
      ('3', 2, 1),
       ('4', 3, 1);

我目前拥有的:

SELECT s.*, COALESCE(v.totalViews, 0) as totalViews 
          FROM survey s
          LEFT JOIN (SELECT id, poll_id, count(id) AS totalViews
          FROM views GROUP BY id) as v on v.poll_id = s.id

我希望结果最终看起来像这样

id  title               url                     totalViews
1   ants on the hill    https://mypoll.io/xyz   1
2   crocs in the swamp  https://mypoll.io/xyz   2
3   baboon on the loose https://mypoll.io/another-term. 1

小提琴示例:http ://sqlfiddle.com/#!9/fb8ede/1

4

3 回答 3

1

您需要对子查询进行细微调整,id从 SELECT 中删除列,因为不需要它,然后poll_id改为GROUP BY

SELECT poll_id, count(id) AS totalViews
      FROM views GROUP BY poll_id
于 2019-09-05T11:13:07.137 回答
1

您正在加入和聚合错误的列。你只想poll_id

SELECT s.*, COALESCE(v.totalViews, 0) as totalViews 
FROM survey s LEFT JOIN
     (SELECT poll_id, count(id) AS totalViews
      FROM views 
      GROUP BY poll_id
     ) v
     ON v.poll_id = s.id;

是一个 SQL 小提琴。

于 2019-09-05T11:13:50.160 回答
0

您不应该在查询中使用sum(count)(而不是)吗?count(id)

SELECT poll_id,title,url, sum(`count`) totalViews FROM survey s
LEFT JOIN views v ON v.poll_id= s.id
GROUP BY poll_id

否则实际count输入views将不会被考虑在您的结果中。

我的小提琴演示

于 2019-09-05T11:27:04.943 回答