如何联接三个表,如何从两个表中添加两个单独的字段,然后最后按两个表中的两个单独的字段进行分组

时间:2019-12-06 11:01:32

标签: mysql

我有三个表admins,table2,table3

管理员结构是

admins_id  | admin_name | admin_username
1          | ABC        |1234
2          | Cde        |456

table2结构是

table2mask |table2adminid | table2maskcount
mask1      |1              |30
mask2      |1              |60

table3结构是

table3mask |table3adminid | table3maskcount
mask1      |1              |30
mask2      |1              |70
mask3      |2              |10

我想要实现的是

username   | mask        |ttlCount
1234       | mask1       | 60
1234       | mask2       | 130
456        | mask3       | 10

我应该如何实现

我尝试使用下面给出的查询

SELECT admins.`admin_username`, 
(table2.`table2maskcount`+table3.`table3maskcount`) AS ttl_counts from 
admins inner join table2 on table2.`table2adminid` = admins.`admin_id` inner 
join table3 on table3.`table3adminid` = admins.`admin_id` Where 
table2.`table2mask`=table3.`table3mask`

但是它不能给我准确的结果,它没有显示仅在两个表之一中可用的蒙版计数

1 个答案:

答案 0 :(得分:2)

admins加入到其他两个表group by adminmask的联合中并进行汇总:

select a.admin_username username, t.mask, sum(maskcount) ttlcount
from admins a inner join (
  select 
    table2mask mask, 
    table2adminid adminid, 
    table2maskcount maskcount 
  from table2
  union all
  select * from table3
) t on t.adminid = a.admins_id 
group by a.admins_id, a.admin_username, t.mask

请参见demo
结果:

| username | mask  | ttlcount |
| -------- | ----- | -------- |
| 1234     | mask1 | 60       |
| 1234     | mask2 | 130      |
| 456      | mask3 | 10       |