如何从多个表中获取查询?

时间:2017-01-31 13:17:22

标签: mysql sql

在我正在处理的数据库中,有14个不同城市的新闻表(table1,table2 .... table14)具有完全相同的结构。一些专栏是: id,作者,日期,news_title,news_body

有不同的作者在相关城市表中发布。现在我想知道今天每个作者在所有14个表格中发布了多少新闻。

以下是输出格式:

author | num_of_post
bob          5
peter        12

请记住,有14个表(这是问题)

1 个答案:

答案 0 :(得分:1)

正如@Grodon已经说过你可以使用这样的联盟:

select author, count(id) as num_of_post from table1 group by author
union
select author, count(id) as num_of_post from table2 group by author
union
select author, count(id) as num_of_post from table3 group by author

等等

更新

由于您有多个表中的1位作者的记录,因此您可以再次对联合结果进行分组。

select author, sum(num_of_post) from (
 select author, count(id) as num_of_post from table1 group by author
 union
 select author, count(id) as num_of_post from table2 group by author
 union
 select author, count(id) as num_of_post from table3 group by author) a group by author