例如有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 运算符的查询表达式中的所有查询都必须在选择列表中包含同样数目的表达式。

解决方案 »

  1.   

    使用UNION 时就得保持A表与B表的列数一致啊,现在A是两列,B是四列,所以出错了。
      

  2.   

    两个表之间的列数不一样.不能用*
    select   姓名,年龄   from   ta   where   姓名   =   'a' 
    union   all 
    select   姓名,年龄   from   tb   where   姓名   =   'a' 
      

  3.   

    select   *   from   

        select   *,' ' 性别   from   ta 
        union   all 
        select   *   from   tb 
    )   t 
    where   姓名   =   'a' 
      

  4.   


    select 姓名,年龄,'' as 性别 from ta where 姓名 = 'a' 
    union all 
    select 姓名,年龄,性别 from tb where 姓名 = 'a'
      

  5.   

    declare @a table (姓名 varchar(10),年龄 int)
    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'
      

  6.   

    但是我希望得出的结果集是这样的:
    姓名      年龄        性别   
    XX       XX        XX如果查出来是TableA中的记录则:
    (没有的就空着)
    姓名      年龄        性别   
    a        11    
         
    如果查出是TableB的:姓名      年龄        性别   
    e        15         male    
      

  7.   

    declare @a table (姓名 varchar(10),年龄 int)
    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'
      

  8.   


    错误提示的已经够明显了。必须包含同样数目
    select 姓名,年龄 from ta where 姓名 = 'a' 
    union all 
    select 姓名,年龄 from tb where 姓名 = 'a'