Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

join on multiple columns

Tags:

sql

tsql

I have two tables (Table A and Table B) which I want to join on multiple columns in both tables.

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.

like image 582
ElegantFellow Avatar asked Aug 24 '11 23:08

ElegantFellow


People also ask

Can you join on multiple columns?

If you'd like to get data stored in tables joined by a compound key that's a primary key in one table and a foreign key in another table, simply use a join condition on multiple columns. In one joined table (in our example, enrollment ), we have a primary key built from two columns ( student_id and course_code ).

How do I join two tables in SQL with all columns?

In SQL the FULL OUTER JOIN combines the results of both left and right outer joins and returns all (matched or unmatched) rows from the tables on both sides of the join clause. Let's combine the same two tables using a full join. Here is an example of full outer join in SQL between two tables.


3 Answers

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 
like image 128
paparazzo Avatar answered Sep 25 '22 00:09

paparazzo


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...

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 ) 
like image 44
DRapp Avatar answered Sep 25 '22 00:09

DRapp


Below is the structure of SQL that you may write. You can do multiple joins by using "AND" or "OR".

Select TableA.Col1, TableA.Col2, TableB.Val
FROM TableA, 
INNER JOIN TableB
 ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2
like image 28
CharithJ Avatar answered Sep 25 '22 00:09

CharithJ