我有两个MySQL表。除了有一个额外的列之外,它们具有相同的结构。我想找出一些实例的数量,其中只有一列“地址”中的记录是相同的。换句话说,我想找到两个表中出现的地址数。
答案 0 :(得分:0)
如果您想要两个表格中的地址数量,请使用union all
和count()
:
select count(distinct address)
from ((select address from table1) union all
(select address from table2)
) t
如果您想要两个表中都存在的地址:
select address
from ((select address, 1 as in1, 0 as in2 from table1) union all
(select address, 0 as in1, 1 as in2 from table2)
) t
group by address
having sum(in1) > 0 and sum(in2) > 0;
您可以使用以下方式获取计数:
select count(*)
from (select address
from ((select address, 1 as in1, 0 as in2 from table1) union all
(select address, 0 as in1, 1 as in2 from table2)
) t
group by address
having sum(in1) > 0 and sum(in2) > 0
) a;
答案 1 :(得分:0)
我想你只想加入这两个表并计算记录:
SELECT COUNT(*)
FROM table1 t1
JOIN table2 t2
ON t1.address = t2.address
如果您想忽略重复项,例如,' 123 Main' 123在table1中出现一次,但在table2中出现两次,上面的查询会将其计算两次,但如果您只想为' 123 Main'计算一次,则还要使用DISTINCT
:
SELECT DISTINCT COUNT(t1.address)
FROM table1 t1
JOIN table2 t2
ON t1.address = t2.address
答案 2 :(得分:0)
您所描述的是内部连接,对于Mysql,它是默认连接。
这是一个匹配数字的例子。注意我将结果限制为5以便于阅读。该示例应该可以很好地扩展到字符串,前提是您可以找到实际匹配字符串的好方法。
mysql> create temporary table test.t1 ( i int unsigned not null );
Query OK, 0 rows affected (0.05 sec)
mysql> create temporary table test.t2 ( i int unsigned not null );
Query OK, 0 rows affected (0.01 sec)
mysql> insert into test.t1 select floor(rand() * 100) from mysql.user;
Query OK, 125 rows affected (0.02 sec)
Records: 125 Duplicates: 0 Warnings: 0
mysql> select test.t1.i, test.t2.i from test.t1 inner join test.t2 on test.t1.i = test.t2.i limit 5;
+----+----+
| i | i |
+----+----+
| 2 | 2 |
| 2 | 2 |
| 24 | 24 |
| 24 | 24 |
| 11 | 11 |
+----+----+
5 rows in set (0.01 sec)