我有以下3个带有嵌套数据的表:
部分表
id title
1 s1
2 s2
3 s3
术语表:
id id_secion
1 1
2 1
3 3
访问表:
id id_term
1 1
2 1
3 1
4 2
5 3
6 3
我需要使用哪种查询或方式来获得这样的结果:
section visit_count
1 4
2 0
3 2
数据库导出是:
CREATE TABLE IF NOT EXISTS `section` (
`id` int(10) NOT NULL,
`title` varchar(5) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `section` (`id`, `title`) VALUES
(1, 's1'),
(2, 's2'),
(3, 's3');
CREATE TABLE IF NOT EXISTS `term` (
`id` int(11) NOT NULL,
`id_section` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `term` (`id`, `id_section`) VALUES
(1, 1),
(2, 1),
(3, 3);
访问表是:
答案 0 :(得分:2)
SELECT s.id AS section, COUNT(v.id_term) AS visit_count
FROM section s
LEFT JOIN term t
ON s.id = t.id_section
LEFT JOIN visit v
ON t.id = v.id_term
GROUP BY s.id
按照以下链接进行正在运行的演示: