简体   繁体   English

MySQL中两个表的总体唯一计数

[英]Overall Unique count from two tables in MySQL

I have two tables, both having column a device_id column that I want to count. 我有两个表,都有一列我想要计算的device_id列。 For the purposes of demonstration, the schema looks like: 出于演示的目的,架构如下所示:

Table 1: 'id', 'save_val', 'device_id_major'
Table 2: 'id', 'save_val', 'location', 'device_id_team'

Table 1 could have many of the same ' device_id_major '. 表1可能有许多相同的' device_id_major '。

I basically want to get the unique device_id's from both tables, then from that result set, get the count of unique device_id's (the same device_id can appear in both tables). 我基本上想要从两个表中获取唯一的device_id,然后从该结果集中获取唯一的device_id的计数(两个表中都可以出现相同的device_id)。

Is this possible in one query? 这可能在一个查询中?

select distinct aa.device_id, count(*) 
from(select distinct device_id from table1
union all
select distinct device_id from table2) as aa
group by device_id
order by device_id

Or something like... As I don't have the schema to hand, I can't fully validate it. 或类似的东西......由于我没有手绘模式,我无法完全验证它。

SELECT count(DISTINCT aa.id) 
FROM (SELECT DISTINCT major_id AS id FROM `major` 
UNION ALL
SELECT DISTINCT team_id AS id FROM `team`) 
AS aa

This seems to do the trick. 这似乎可以解决问题。

您可以使用获取两个表的UNION的查询,然后选择唯一值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM