联表查询 table_a 和 table_b: 已知: 1.table_a和table_b中有个'time'字段对应。 2.table_a中的一条记录table_b中可能有0~n条记录与之对应。 查询: table_a中的所有记录,每条记录对应的table_b中的记录数量
table_a:
id | name | time | @H_403_8@1 | name1 | 123 | @H_403_8@2 | name2 | 456 | @H_403_8@3 | name3 | 789 |
---|
table_b:
id | time | path | @H_403_8@1 | 123 | /a/b/123a.txt | @H_403_8@2 | 123 | /a/b/123b.txt | @H_403_8@3 | 123 | /a/b/123c.txt | @H_403_8@4 | 456 | /a/b/123c.txt |
---|
想要的查询结果是:
id | name | time | count(对应table_b中的记录数) | @H_403_8@1 | name1 | 123 | 3 | @H_403_8@2 | name2 | 456 | 1 | @H_403_8@3 | name3 | 789 | 0 |
---|
sql 语句如下:
SELECT table_a.id,table_a.name,table_a.time as time,COUNT(table_b.time) AS count FROM table_a LEFT JOIN table_b ON table_a.time = table_b.time GROUP BY table_b.time
如果只需要知道table_b中是否有对应记录,而不需要知道具体的数量,那么可以把第一行修改为(添加 DISTINCT ):
SELECT table_a.id,COUNT(DISTINCT table_b.time) AS count ...
注意: GROUP BY 和 COUNT 后面是同一张表的同一个字段