How to retrieve match records across multiple tables in MySQL

不羁的心 提交于 2019-12-30 10:59:44

问题


I have two identical tables such as :

table1
col1    col2    col3    col4    col5

table2
col1    col2    col3    col4    col5

I want to compare table 1 and 2 and find identical rows (col1, col2, col3, col4 etc..) between the 2 tables.

I think we need to use vtable or something similar ..

I tried

SELECT * FROM TABLE1 WHERE COL1, COL2, COL3, COL4 IN 
        (SELECT COL1, COL2, COL3, COL4 FROM TABLE2);

It doesn't work .. help please :)


回答1:


SELECT * 
FROM TABLE1 t
WHERE EXISTS
      ( SELECT *
        FROM TABLE2 tt
        WHERE (COL1, COL2, COL3, COL4) 
            = (t.COL1, t.COL2, t.COL3, t.COL4)
      )
;



回答2:


Oracle syntax, which I'm sure is nearly identical in MySql:

 SELECT *
   FROM TABLE1, TABLE2
  WHERE TABLE1.COL1 = TABLE2.COL1
    AND TABLE1.COL2 = TABLE2.COL2
    AND TABLE1.COL3 = TABLE2.COL3
    AND TABLE1.COL4 = TABLE2.COL4

There might be a more elegant and clever way, but that'll find your duplicates.




回答3:


How about:

SELECT table1.* FROM table1
  INNER JOIN table1 ON table2.col1 = table1.col1
  WHERE table1.col2 = table2.col2 AND table1.col3 = table2.col3
    AND table1.col4 = table2.col4 AND table1.col5 = table2.col5


来源:https://stackoverflow.com/questions/10266180/how-to-retrieve-match-records-across-multiple-tables-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!