我试图加入两个包含多列的表

时间:2017-12-12 12:06:54

标签: sql database join

我的第一张表如下:

ID; sip1; sip2; sip3; sip4;

01 ;  A1 ; A2   

02 ; B1 ; B2;  B3 ;   B4;

03 ; C1  ;C2 ; C3;

第二张表,

SipX ; V1

A1   ; a

A2   ; b

B3   ; c

C2   ; d

我如何加入这两张桌子? 我试过了:

select * from firts_table a 
inner join second _table b on a.sip1 = b.sipx 
inner join second_table c on a.sip2 = c.sipx
inner join second_table d on a.sip3 = d.sipx
inner join second_table e on a.sip2 = e.sipx

它没有用。 我期待展示:

ID; Sipx ; V1

01; A1 ; a
01; A2 ; b
02; B3 ; c
03; C2 ; d

*

2 个答案:

答案 0 :(得分:0)

SELECT
    table_one.ID,
    table_two.*
FROM
   table_one
INNER JOIN
   table_two
       ON  table_two.SipX IN (table_one.sip1, table_one.sip2, table_one.sip3, table_one.sip4)

答案 1 :(得分:0)

尝试此查询

   IF OBJECT_ID ('firsttable') IS NOT NULL
    DROP TABLE firsttable
GO

CREATE TABLE firsttable
    (
    id   INT NULL,
    sip1 VARCHAR (20) NULL,
    sip2 VARCHAR (20) NULL,
    sip3 VARCHAR (20) NULL,
    sip4 VARCHAR (20) NULL
    )
GO

IF OBJECT_ID ('secondtable') IS NOT NULL
    DROP TABLE secondtable
GO

CREATE TABLE secondtable
    (
    sipx VARCHAR (20) NULL,
    v1   VARCHAR (20) NULL
    )
GO



    select a.id,a.sip1 AS SIP1,b.v1 AS SIP1_V1,
                a.sip2 AS SIP2,c.v1 AS SIP2_V1,
                a.sip3 AS SIP3,d.v1 AS SIP3_V1,
                a.sip4 AS SIP4,e.v1 AS SIP4_V1
                 from firsttable a 
LEFT OUTER join secondtable b on a.sip1 = b.sipx 
LEFT OUTER join secondtable c on a.sip2 = c.sipx
LEFT OUTER join secondtable d on a.sip3 = d.sipx
LEFT OUTER join secondtable e on a.sip2 = e.sipx