带有一个唯一列的SQL两个表

时间:2011-12-01 15:04:28

标签: sql sql-server sql-server-2008

我有两个表tbl_backupchecks和tbl_backupchecks_sqlbak。

两个表都有两个列名,Company和ServerName。

我想返回一个包含公司和Servername的结果集,但是在合并列表中。基本上如果tbl_backupchecks_SQLBak中的服务器名和公司名不在tbl_backupchecks中,我也想报告它。

在基本术语中,我想要一个两列的行结果集;公司和服务器名称。我尝试写一个左连接,但它买回了两个名为ServerName的列。可以这样做吗?

9 个答案:

答案 0 :(得分:5)

假设您的列CompanyServername是可以是DISTINCT的数据类型,您可以使用UNION查询:

SELECT Company, Servername FROM tbl_backupchecks
UNION
SELECT Company, Servername FROM tbl_backupchecks_sqlbak

答案 1 :(得分:0)

我认为工会应该为你做这件事

   SELECT Company, ServerName
   FROM tbl_backupchecks
   UNION
   SELECT Company, ServerName
   FROM tbl_backupchecks_sqlbak

答案 2 :(得分:0)

使用UNION:

SELECT  Company, ServerName 
  FROM  tbl_backupchecks 
UNION
SELECT  Company, ServerName 
  FROM  tbl_backupchecks_sqlbak 

答案 3 :(得分:0)

我想你想要一个UNION:

对于两个表之间的不同行,请使用:

SELECT Company,ServerName
FROM tbl_backupchecks
UNION
SELECT Company,ServerName
FROM tbl_backupchecks_sqlbak

对于来自两个表的所有行(不会删除两个表中存在的重复行),请使用:

SELECT Company,ServerName
FROM tbl_backupchecks
UNION ALL
SELECT Company,ServerName
FROM tbl_backupchecks_sqlbak

答案 4 :(得分:0)

SELECT Company, ServerName FROM tbl_backupchecks

UNION

SELECT Company, ServerName FROM tbl_backupchecks_sqlbak

(如果您想保留重复项,请将UNION更改为UNION ALL。)

答案 5 :(得分:0)

如果您只想要两者的唯一记录,请使用:

SELECT DISTINCT Company, ServerName
FROM
(
SELECT Company, ServerName FROM tbl_backupchecks
UNION
SELECT Company, ServerName FROM tbl_backupchecks_sqlbak
) A

答案 6 :(得分:0)

我想你想要两个表的联合。类似的东西:

SELECT Company, ServerName FROM tbl_backupchecks
UNION 
SELECT Company, ServerName FROM tbl_backupchecks_SQLBak

答案 7 :(得分:0)

我发现这可能对你有所帮助。我最初是一个联盟,但这似乎是一种更好的方式:t-sql-comparing-two-tables-records-that-dont-exist-in-second-table

答案 8 :(得分:0)

这是一个解决方案,也告诉你记录在哪里

select Company, ServerName, sum(case when is_bak=0 then 0 else 1) as in_bak, sum(case when is_bak=0 then 1 else 0) as in_not_bak from (
select Company, ServerName,0 as is_bak from tbl_backupchecks union 
select  SELECT Company, ServerName, 1 as is_bak FROM tbl_backupchecks_SQLBak
) group by Company, ServerName