SQL Server 2012: JOIN 3 tables for a condition

假装没事ソ 提交于 2019-12-13 04:52:20

问题


I have 3 tables: TABLEA (ID INT, name VARCHAR(2))

ID  Name 
01  A4
01  SH
01  9K
02  M1
02  L4
03  2G
03  99

TableB(Name VARCHAR(2))

Name 
5G
U8
02
45
23
J7
99
9F
A4
H2....

TableC(ID INT, Name VARCHAR(2)) (prepopulated with ID from tableA) (same number of records as A)

ID  Name 
01  NULL
01  NULL
01  NULL
02  NULL
02  NULL
03  NULL
03  NULL

I want to populate C.Name from B.Name so that for same ID (say 1), it should have different values than A.Name . So, C.Name can not have (A4, SH, 9K) for ID = 1 because they already exist in A.name. Also, A.name may or maynot exist in B.name.

Problem here is that I dont have additional columns in tableB. Do I need more columns to JOIN my tables? Thanks for your help!


回答1:


You can do this with a rather inefficient, nested query structure in an update clause.

In SQL Server syntax:

update tableC
    set Name = (select top 1 b.name
                from TableB b 
                where b.name not in (select name from TableA a where a.id = TableC.id)
                order by NEWID()
               )

The inner most select from TableA gets all the names from the same id. The where clause chooses names that are not in this list. The order by () limit 1 randomly selects one of the names.

Here is an example of the code that works, according to my understanding of the problem:

declare @tableA table (id int, name varchar(2));
declare @tableB table (name varchar(2));
declare @tableC table (id int, name varchar(2))

insert into @tableA(id, name)
    select 01, 'A4' union all
    select 01, 'SH' union all
    select 01, '9K' union all
    select 02, 'M1' union all
    select 02, 'L4' union all
    select 03, '2G' union all
    select 03, '99';

insert into @tableB(name)
    select '5G' union all
    select 'U8' union all
    select '02' union all
    select '45' union all
    select '23' union all
    select 'J7' union all
    select '99' union all
    select '9F' union all
    select 'A4' union all
    select 'H2';


insert into @tableC(id)
    select 01 union all
    select 01 union all
    select 01 union all
    select 02 union all
    select 02 union all
    select 03 union all
    select 03;

/*    
select * from @tableA;
select * from @tableB;
select * from @tableC;
 */

update c
    set Name = (select top 1 b.name
                from @TableB b 
                where b.name not in (select name from @TableA a where a.id = c.id)
                order by NEWID()
               )
from @tableC c

select *
from @tableC


来源:https://stackoverflow.com/questions/16490625/sql-server-2012-join-3-tables-for-a-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!