按列类型连接

时间:2015-11-08 18:09:19

标签: sql-server join

我有两张如下表格。

id1 | val | type
1     2     type1
1     4     type2
2     9     type2
2     7     type1

id2|type1|type2
11  2      4
33  7      9

 I need result like this
id1|id2
1   11
2    33

我需要检查type1和type2以关联id1和id2。我尝试了以下查询,但它不起作用。

 select id1,id2 from t1 inner join t2 on (type='type1' and                             
 t1.val=t2.type1)and (type='type2' and t1.val=t2.type2)

2 个答案:

答案 0 :(得分:1)

我相信这会给你你想要的东西:

SELECT
    a.id1,
    t2.id2
FROM
    t2
INNER JOIN
    t1 a ON a.val = t2.type1 AND a.type = 'type1'
INNER JOIN
    t1 b ON b.val = t2.type2 AND b.type = 'type2'
WHERE
    a.id1 = b.id1

答案 1 :(得分:1)

SQL Fiddle

MS SQL Server 2008架构设置

CREATE TABLE t1(id1 INT,  val INT,  [type] VARCHAR(10))
INSERT INTO t1 VALUES
(1 ,    2     ,'type1'),
(1 ,    4     ,'type2'),
(2 ,    9     ,'type2'),
(2 ,    7     ,'type1')


CREATE  TABLE t2(id2 INT,  [type1] VARCHAR(10),  [type2] VARCHAR(10))
INSERT INTO t2 VALUES
(11 , 2  ,    4),
(33 , 7  ,    9)

查询1

Select t1.id1 , t2.id2 
from t1
inner join 
(Select * from t2 t 
      UNPIVOT (Val for [type]  IN ([type1],[type2]))up) t2
ON t1.val = t2.Val and t1.type = t2.type
GROUP BY t1.id1 , t2.id2

<强> Results

| id1 | id2 |
|-----|-----|
|   1 |  11 |
|   2 |  33 |