Mysql SQL查询应该聚合每行数据,而不是多行数据
我希望列出每行调查的总视图:Mysql SQL查询应该聚合每行数据,而不是多行数据,mysql,sql,Mysql,Sql,我希望列出每行调查的总视图: 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`, `ti
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
示例Fiddle:您需要对子查询做一个小的调整,从SELECT中删除
id
列,因为它不是必需的,而是在poll\u id
上进行分组
SELECT poll_id, count(id) AS totalViews
FROM views GROUP BY poll_id
您在错误的列上加入和聚合。您只需要
poll\u 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提琴。您不应该在查询中使用
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
否则,视图
中的实际计数将不会考虑在结果中
看