如何显示2个表中的所有重复行?

问题描述:

我有两个名为DataEntry_old和DataEntry_new的表,它们在两个表上都有列doc id,mobileno,name,addr。如何显示2个表中的所有重复行?

我想显示两个表中的所有匹配行,其中mobileno = 987654321。 也就是说,如果mobileno = 987654321在DataEntry_old中,则表中有一行,如果还有mobileno = 987654321在DataEntry_new中,则表中的另一行。

+5

** **什么数据库系统,以及哪个版本? * SQL *只是*结构化查询语言* - 许多数据库系统使用的语言,但不是数据库产品......类似这样的东西通常是供应商特定的 - 所以我们真的需要知道什么**数据库系统**你正在使用.... – 2012-07-24 09:38:25

+1

似乎是[union all]的工作(http://en.wikipedia.org/wiki/Set_operations_%28SQL%29#UNION_operator)。 – 2012-07-24 09:39:10

+1

欢迎来到*!你可以编辑你的问题并添加适当的标签(比如SQL-Server,MySQL等)。这将帮助我们帮助你! – Josien 2012-07-24 09:48:27

SELECT doc_id, mobileno, name, addr 
FROM DataEntry_old 
    ,DataEntry_new 
WHERE DataEntry_ol.doc_id = DataEntry_new.doc_id 
+1

不要使用SQL-89风格的语法,特别是在教授新用户时 - 在进行一些复杂的连接时,它有未定义的结果...'SELECT * FROM DataEntry_old O INNER JOIN DataEntry_new N ON O.mobileno = N.mobileno' – Basic 2012-07-24 09:57:06

+0

但它返回两个表中匹配的数据在单个行中的两次 – 2012-07-24 09:59:51

SELECT doc_id, mobileno, name, addr FROM DataEntry_old o inner join DataEntry_new n 
on o.doc_id=n.doc_id 
where n.mobileno='987654321' 
+0

试用N错误....使用了Union All ... thankx – 2012-07-24 10:14:59

您想使用UNION ALL此查询:

select t.* 
from ((select 'old' as which, doc id, mobileno, name, addr 
     from DataEntry_old 
    ) union all 
     (select 'new' as which, doc id, mobileno, name, addr 
     from DataEntry_new 
    ) 
    ) t 
where t.mobileno='987654321'