动态JOIN条件

时间:2015-10-05 02:26:03

标签: sql sql-server sql-server-2012 inner-join

我有桌子:

Tbl1
+----+------+
| id | type |
+----+------+
| 1  |  11  | 
| 1  |  22  | 
| 2  |  *   |
+----+------+


Tbl2
+----+------+------+
| id | type | name |
+----+------+------+
| 1  |  11  | AAA  |
| 1  |  22  | BBB  |
| 2  |  11  | CCC  |
| 2  |  22  | DDD  |
+----+------+------+

我想加入id和类型。但如果输入=' *'我想得到所有类型。 如何加入Tbl1和Tbl2来实现这个结果?

类似的东西:

SELECT a.* FROM Tbl2 a 
INNER JOIN Tbl1 b ON a.id = b.id  
AND a.type = b.type ?? (i want use case statement to achieve this result)

result
+----+------+------+
| id | type | name |
+----+------+------+
| 1  |  11  | AAA  |
| 1  |  22  | BBB  |
| 2  |  11  | CCC  |
| 2  |  22  | DDD  |
+----+------+------+

1 个答案:

答案 0 :(得分:0)

您可以在on子句中包含条件:

SELECT a.*
FROM Tbl2 a INNER JOIN
     Tbl1 b
     ON a.id = b.id AND
        (a.type = b.type OR a.type = '*' OR b.type = '*');

目前还不清楚您是否打算将通配符应用于两个表或仅应用于一个表。如果是,则删除a.type = '*'上的条件。