2

所以这是我的设置,我有 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 

谢谢!

4

2 回答 2

2

您是否尝试过 JOIN 语句:

select distinct * 
from old a join new b on a.ManName = b. Manager_Name and a. ManNumber = b. Manager_Number
于 2013-07-25T17:44:56.587 回答
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

一个用于测试的 SQLfiddle

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

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

另一个 SQLfiddle

于 2013-07-25T17:54:31.657 回答