读书人

怎么得到2个表(或以上)共有相同字段

发布时间: 2012-02-12 17:16:33 作者: rapoo

如何得到2个表(或以上)共有相同字段的数据的数量呢?在线给分
table1: name, id,……
table2: name, id,……

我想得到当指定name和id的时候,在table1和table2一共有多少条记录,该怎么写呢?谢谢

[解决办法]
select count(*) from (
select 1 from table1 where name=值 and id=值
union all
select 1 from table2 where name=值 and id=值
)

[解决办法]
select name,id,... from table1 where name=值 and id=值
union [ALL] --加ALL不自动取掉重复
select name,id,... from table2 where name=值 and id=值

--两处的...字段类型必须相同
[解决办法]
select sum([count]) as [count]
from (select count(*) as [count] from table1 where name=值 and id=值
union
select count(*) from table2 where name=值 and id=值)t

读书人网 >SQL Server

热点推荐