SQL 加入多列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7183364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
join on multiple columns
提问by ElegantFellow
I have two tables (Table A and Table B) which I want to join on multiple columns in both tables.
我有两个表(表 A 和表 B),我想在两个表中的多个列上加入它们。
Table A
Col1 Col2
================
A11 A21
A22 A22
A33 A23
Table B
Col1 Col2 Val
=================
B11 B21 1
B12 B22 2
B13 B23 3
I want both Columns in Table A to join on either of Col1 and Col2 in Table B to get Val.
我希望表 A 中的两列都加入表 B 中的 Col1 和 Col2 中的任何一个以获得 Val。
回答by paparazzo
Agree no matches in your example.
If you mean both columns on either then need a query like this or need to re-examine the data design.
同意您的示例中没有匹配项。
如果您的意思是两个列都需要这样的查询,或者需要重新检查数据设计。
Select TableA.Col1, TableA.Col2, TableB.Val
FROM TableA
INNER JOIN TableB
ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2
OR TableA.Col2 = TableB.Col1 OR TableA.Col1 = TableB.Col2
回答by DRapp
The other queries are all going base on any ONE of the conditions qualifying and it will return a record... if you want to make sure the BOTH columns of table A are matched, you'll have to do something like...
其他查询都基于任何一个符合条件的条件,它会返回一条记录......如果你想确保表 A 的两列都匹配,你必须做类似的事情......
select
tA.Col1,
tA.Col2,
tB.Val
from
TableA tA
join TableB tB
on ( tA.Col1 = tB.Col1 OR tA.Col1 = tB.Col2 )
AND ( tA.Col2 = tB.Col1 OR tA.Col2 = tB.Col2 )
回答by CharithJ
Below is the structure of SQL that you may write. You can do multiple joins by using "AND" or "OR".
以下是您可以编写的 SQL 结构。您可以使用“AND”或“OR”进行多个连接。
Select TableA.Col1, TableA.Col2, TableB.Val
FROM TableA,
INNER JOIN TableB
ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2
回答by gview
tableB.col1 = tableA.col1
OR tableB.col2 = tableA.col1
OR tableB.col1 = tableA.col2
OR tableB.col1 = tableA.col2