全部在查询中。下面的查询将为您提供每个国家、用户类型和包的计数结果。显然,您可以使用循环来创建 12 个表联合,但为了便于阅读,我将其全部写下来。
还要记住使用 UNION ALL 而不仅仅是 UNION。如果使用 UNION 会丢弃重复行,但是如果表 1 的某个组的计数为 100,而表 2 的同一组也有 100,则您要返回 100 两次,因此总和为 200。如果您使用 UNION 它会返回 100 一次,总和显然也是 100。
SELECT SUM(cnt) as total, `country`, `usertype`, `package` FROM
(
SELECT COUNT(country) as cnt, `country`, `usertype`, `package` FROM table1 GROUP BY `country`, `usertype`, `package`
UNION ALL
SELECT COUNT(country) as cnt, `country`, `usertype`, `package` FROM table2 GROUP BY `country`, `usertype`, `package`
UNION ALL
SELECT COUNT(country) as cnt, `country`, `usertype`, `package` FROM table3 GROUP BY `country`, `usertype`, `package`
UNION ALL
SELECT COUNT(country) as cnt, `country`, `usertype`, `package` FROM table4 GROUP BY `country`, `usertype`, `package`
UNION ALL
SELECT COUNT(country) as cnt, `country`, `usertype`, `package` FROM table5 GROUP BY `country`, `usertype`, `package`
UNION ALL
SELECT COUNT(country) as cnt, `country`, `usertype`, `package` FROM table6 GROUP BY `country`, `usertype`, `package`
UNION ALL
SELECT COUNT(country) as cnt, `country`, `usertype`, `package` FROM table7 GROUP BY `country`, `usertype`, `package`
UNION ALL
SELECT COUNT(country) as cnt, `country`, `usertype`, `package` FROM table8 GROUP BY `country`, `usertype`, `package`
UNION ALL
SELECT COUNT(country) as cnt, `country`, `usertype`, `package` FROM table9 GROUP BY `country`, `usertype`, `package`
UNION ALL
SELECT COUNT(country) as cnt, `country`, `usertype`, `package` FROM table10 GROUP BY `country`, `usertype`, `package`
UNION ALL
SELECT COUNT(country) as cnt, `country`, `usertype`, `package` FROM table11 GROUP BY `country`, `usertype`, `package`
UNION ALL
SELECT COUNT(country) as cnt, `country`, `usertype`, `package` FROM table12 GROUP BY `country`, `usertype`, `package`
) temp
GROUP BY `country`, `usertype`, `package`
附带说明:您不必这样做
$stat_array[$country][$usertype][$package]= 1 + $stat_array[$country][$usertype][$package];
你可以这样做:
$stat_array[$country][$usertype][$package]++;
最后,如果您使用像您这样的多维数组,则在内部必须进行大量检查。简单地说,它会首先在数组中找到正确的国家,这将给出另一个数组。它将在该数组中找到用户类型,然后在第三个数组中再次执行相同的操作。
如果 $country、$usertype 和 $package 都是字符串,你最好加入字符串并使用它。
$key = $country.'_'.$usertype.'_'.$package;
$stat_array[$key]++;
但我想这一切都取决于一旦你将数据存储在数组中,你想对它做什么。如果它只是打印总计数,您甚至不需要数组,而是直接在查询结果循环中打印。