如何选择未拼写的行

时间:2015-07-27 06:18:56

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

create table user_info(
    userID int,
    names varchar(20),
    fatherName varchar(20),
    grade varchar(10),
    status varchar(20)
)

insert into user_info values(001,'raj singh','venkatesh','A','active')
insert into user_info values(008,'atal bihari','ram pratap','c','departed') 
insert into user_info values(005,'sultaan mirja','jai khan','b','active')
insert into user_info values(009,'faiz ali','mahboob ali','d','termineted')
insert into user_info values(003,'david sam','david rk','A','awarded')

userID  names           fatherName     grade   status
----------------------------------------------------
001     raj singh       venkatesh      A       active
008     atal bihari     ram pratap     c       departed
005     sultaan mirja   jai khan       b       active 
009     faiz ali        mahboob ali    d       termineted 
003     david sam       david rk       A       awarded 

第二张表:

create table user_contact(
    userID int,
    contectNo int,
    houseNo varchar(20),
    city varchar(20),
    grade varchar(10)
)

insert into user_contact values(001,'2586931475','384 b block','ludhiyan','A')
insert into user_contact values(005,'9817588937','786 sector 4','lahore','b')
insert into user_contact values(0010,'8081829973','164 p.road','kanpur','A')
insert into user_contact values(0011,'7898654532','132 ram janki puram','ayodhya','c')
insert into user_contact values(009,'8978231254','420 coco-cola','limka','e')

userID    contectNo      houseNo               city            grade  
--------------------------------------------------------------------
001       2586931475     384 b block           ludhiyan        A 
005       9817588937     786 sector 4          lahore          b 
0010      8081829973     164 p.road            kanpur          A 
0011      7898654532     132 ram janki puram   ayodhya         c 
009       8978231254     420 coco-cola         limka           e 

我想结果:

names           fatherName          contectNo             city 
------------------------------------------------------------------
atal bihari     ram pratap          null                  null
david sam       david rk            null                  null        
null            null                8081829973            kanpur  
null            null                7898654532            ayodhya

2 个答案:

答案 0 :(得分:5)

使用FULL OUTER JOIN

SELECT ui.names,
       ui.fathername,
       uc.contectNo,
       uc.city
FROM   user_contact uc
       FULL OUTER JOIN user_info ui
                    ON uc.userID = ui.userID
WHERE  ui.userID IS NULL
        OR uc.userID IS NULL 

答案 1 :(得分:3)

首先,几件事:

  1. 当您声明string时,您无法存储int
  2. 尝试将AUTO INCREMENTED PK用作ID而不是001或002(甚至,这些将仅存储为1和2,因为类型为int )。
  3. <强>解: 使用FULL OUTER JOIN

    FULL OUTER JOIN背后的想法是,你想要制作一个产品来保存每一行而不管它们是否存在于两个表中。

    检查SQLFIDDLE