我有20个表Table100到Table119,所有表都有相同的结构,Name,StaffID,DeptID,Description
是否可以通过MySQL计算不同的名称,计算不同的StaffID,每个表的记录数?即20次?
输出类似于
Table100, 12, 15, 120
Table101, 10, 10, 130
etc..
可以添加其他表格,但它们都将以“Tablexxx”
开头我可以使用PHP / Perl执行此操作,但我希望通过本机SQL运行它。
由于
答案 0 :(得分:2)
您需要构建一个查询来执行此操作,例如:
select 'Table100' as which, count(distinct name) as NumNames, count(distinct StaffId) as NumStaff, count(*) as NumRecs from Table100 union all
select 'Table101' as which, count(distinct name) as NumNames, count(distinct StaffId) as NumStaff, count(*) as NumRecs from Table101 union all
select 'Table102' as which, count(distinct name) as NumNames, count(distinct StaffId) as NumStaff, count(*) as NumRecs from Table102 union all
. . .
select 'Table120' as which, count(distinct name) as NumNames, count(distinct StaffId) as NumStaff, count(*) as NumRecs from Table120;
在SQL中,无法“循环”一组表。你必须明确提到它们。您可以在应用程序中构造查询。或者,您可以使用Excel等工具构建查询。
尽管如此,许多具有相同格式的表都表明数据结构存在问题。通常,最好将这些数据存储在一个表中,而不是分散在许多表中。