例如有2个表
tableA tableB
姓名 年龄 姓名 年龄 性别
a 11 e 15 male
b 12 f 16 female
c 13 g 17 male
d 14 h 18 female 根据姓名来进行查询,
表A与表B的记录不会重复
例如查找姓名为a的,能在A表中查到,则从A表中读出该条记录;
如查找姓名为e的,在A表中不能查到,则到B表中去查. 如何写这样的SQL语句?
谢谢各位大大们===============================================================================
这个问题我问过一次,大家给的答案是:
--这个快一些
select * from ta where 姓名 = 'a'
union all
select * from tb where 姓名 = 'a'--这个慢
SQL codeselect * from
(
select * from ta
union all
select * from tb
) t
where 姓名 = 'a'===============================================================================
但是SQL SERVER会报错:
服务器: 消息 8157,级别 16,状态 1,行 1
包含 UNION 运算符的查询表达式中的所有查询都必须在选择列表中包含同样数目的表达式。
tableA tableB
姓名 年龄 姓名 年龄 性别
a 11 e 15 male
b 12 f 16 female
c 13 g 17 male
d 14 h 18 female 根据姓名来进行查询,
表A与表B的记录不会重复
例如查找姓名为a的,能在A表中查到,则从A表中读出该条记录;
如查找姓名为e的,在A表中不能查到,则到B表中去查. 如何写这样的SQL语句?
谢谢各位大大们===============================================================================
这个问题我问过一次,大家给的答案是:
--这个快一些
select * from ta where 姓名 = 'a'
union all
select * from tb where 姓名 = 'a'--这个慢
SQL codeselect * from
(
select * from ta
union all
select * from tb
) t
where 姓名 = 'a'===============================================================================
但是SQL SERVER会报错:
服务器: 消息 8157,级别 16,状态 1,行 1
包含 UNION 运算符的查询表达式中的所有查询都必须在选择列表中包含同样数目的表达式。
select 姓名,年龄 from ta where 姓名 = 'a'
union all
select 姓名,年龄 from tb where 姓名 = 'a'
(
select *,' ' 性别 from ta
union all
select * from tb
) t
where 姓名 = 'a'
select 姓名,年龄,'' as 性别 from ta where 姓名 = 'a'
union all
select 姓名,年龄,性别 from tb where 姓名 = 'a'
insert into @a select 'a',11
union all
select 'b',12
union all
select 'c',13
union all
select 'd',14declare @b table (姓名 varchar(10),年龄 int,性别 varchar(10))
insert into @b select 'e',15,'male'
union all
select 'f',16,'female'
union all
select 'g',17,'female'
union all
select 'h',18,'female'
select 姓名, 年龄,'' from @a where 姓名 = 'a'
union all
select 姓名, 年龄,性别 from @b where 姓名 = 'a'
姓名 年龄 性别
XX XX XX如果查出来是TableA中的记录则:
(没有的就空着)
姓名 年龄 性别
a 11
如果查出是TableB的:姓名 年龄 性别
e 15 male
insert into @a select 'a',11
union all
select 'b',12
union all
select 'c',13
union all
select 'd',14declare @b table (姓名 varchar(10),年龄 int,性别 varchar(10))
insert into @b select 'e',15,'male'
union all
select 'f',16,'female'
union all
select 'g',17,'female'
union all
select 'h',18,'female'
select 姓名, 年龄,''性别 from @a where 姓名 = 'a'
union all
select 姓名, 年龄,性别 from @b where 姓名 = 'a'
错误提示的已经够明显了。必须包含同样数目
select 姓名,年龄 from ta where 姓名 = 'a'
union all
select 姓名,年龄 from tb where 姓名 = 'a'