简体   繁体   English

如何检查两个不同表中两列数据的存在? 的MySQL

[英]How to check the existence of two columns' data in two different tables ? MySQL

I have two different tables in two different databases .. 我在两个不同的数据库中有两个不同的表..

what I want to do is to check if the data of two columns exist in the other table .. if it does exist count it and at the final I want the number of records that have matching in the other table. 我想做的是检查另一表中是否存在两列的数据..如果确实存在,请对其进行计数,最后我要在另一表中具有匹配项的记录数。

example : 例如:

table_1 表格1

column_1 value = "dog" column_1值=“狗”

column_2 value = "apple" column_2值=“苹果”

table_2 table_2

column_1 value = "dog" column_1值=“狗”

column_2 value = "orange" column_2值=“橙色”

so here the first column values exist in both table but the second column is different so I don't want to count it .. I want to count where both values exist in the same record . 所以这里第一列的值在两个表中都存在,但是第二列是不同的,所以我不想计算它..我想计算两条值在同一记录中的位置。

ps: Both column_1 and column_2 aren't primary key ps:column_1和column_2都不是主键

is there a solution for it using MySQL ? 使用MySQL有解决方案吗? because I used java to solve this but take a long time for 5 million records . 因为我用java解决了这个问题,但是花了500万条记录很长的时间。

Do an INNER JOIN on both tables: 在两个表上进行INNER JOIN

SELECT COUNT(*)
FROM table_1 t1
INNER JOIN table_2 t2
    ON t1.column_1 = t2.column_1
    AND t1.column_2 = t2.column_2

If I'm understanding you correctly, one option is to use exists : 如果我对您的理解正确,则可以使用exists一种选择:

select * 
from table1 t1
where exists (
    select 1
    from table2 t2 
    where t1.column1 = t2.column1 and
          t1.column2 = t2.column2
)

This will return a list of rows from the first table that have a corresponding matching row in the second. 这将返回第一个表的行列表,第二个表中具有对应的匹配行。

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

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