我希望在每行调查中列出总视图:
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