MySQL,如何在不同的表上连接和分组两列

时间:2019-07-09 20:04:54

标签: mysql mariadb

我在mysql中有两个表:

sh

我想要的是将两个表中的“ ip”列合并在一起,然后按ip分组,然后返回被分组的相同ip的数量。

示例结果:

table name = 'static':
+----+----------+-----------+
| id | username | ip        |
+----+----------+-----------+
| 1  | foo      | 172.0.0.1 |
+----+----------+-----------+
| 2  | bar      | 172.0.0.2 |
+----+----------+-----------+
| 3  | baz      | 172.0.0.3 |
+----+----------+-----------+

table name = 'dynamic':
+----+----------+-----------+
| id | username | ip        |
+----+----------+-----------+
| 1  | bill     | 172.0.0.1 |
+----+----------+-----------+
| 2  | ben      | 172.0.0.4 |
+----+----------+-----------+
| 3  | hen      | 172.0.0.5 |
+----+----------+-----------+

1 个答案:

答案 0 :(得分:0)

您不需要加入,但需要UNION ALL,然后进行分组:

select t.ip, count(*) quantity from (
  select ip from static
  union all
  select ip from dynamic
) t
group by t.ip