SQL从多个表中选择不同的值

时间:2013-07-25 17:29:42

标签: sql distinct

所以这是我的设置我有2个表旧的和新的以及(简化的)模式

Old
[ManName]
[ManNumber]

New
[Manager_Name]
[Manager_Number]

我正在寻找一个SQL查询,它返回以下但在1个查询中的4列中,而不是每个2列的2个查询

select distinct manname, mannumber from OLD 
select distinct Manager_Name, Manager_Number from NEW

所以我理想的结果集将有4列:

ManName ManNumber Manager_Name Manager Number 

谢谢!

2 个答案:

答案 0 :(得分:1)

您是否尝试过JOIN语句:

select distinct * 
from old a join new b on a.ManName = b. Manager_Name and a. ManNumber = b. Manager_Number

答案 1 :(得分:1)

几乎使用除MySQL以外的任何RDBMS,你都可以使用CTE和ROW_NUMBER();

WITH cteOld AS (
  SELECT DISTINCT ManName, ManNumber, 
         ROW_NUMBER() OVER (ORDER BY ManNumber) rn FROM Old
), cteNew AS (
  SELECT DISTINCT Manager_Name, Manager_Number,
         ROW_NUMBER() OVER (ORDER BY Manager_Number) rn FROM New
)
SELECT ManName, ManNumber, Manager_Name, Manager_Number 
FROM cteOld
FULL OUTER JOIN cteNew
  ON cteOld.rn=cteNew.rn

An SQLfiddle to test with

另一种更容易获得所有这些的方法是简单地使用UNION;

SELECT ManName, ManNumber, 0 isNew FROM Old
UNION 
SELECT Manager_Name, Manager_Number, 1 FROM New

Another SQLfiddle