Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Join two table with key into different column

Tags:

sql

sql-server

I have two table, in SQL; the first table(T1) is this:

ID  
----
401 
402
403
634
635
636

The second table(T2) is this:

ID1 | VALUE1 | ID2 | VALUE2
---- -------- ----- -------
401 | TEST   | 634 | SAMPLE1
402 | MYVAL  | 635 | TRUE

The result i need is this:

T1.ID | T2.ID1| T2.VALUE1 | T2.ID2 | T2.VALUE2
------ ------- ----------- -------- ----------
401   | 401   | TEST      | 634    | SAMPLE1
402   | 402   | MYVAL     | 635    | TRUE
634   | 401   | TEST      | 634    | SAMPLE1
635   | 402   | MYVAL     | 635    | TRUE

The value 403 and 636 of T1 must not be present in the result because don't have any reference in T2.

There is a way to accomplish this with some INNER JOIN? I'm using MS SQL Server 2017.

like image 288
MrTex Avatar asked Jun 15 '26 07:06

MrTex


1 Answers

Wouldn't this just be in IN clause?

SELECT *
FROM dbo.Table1 T1
     JOIN dbo.Table2 T2 ON T1.ID IN (T2.ID1,T2.ID2)

DB<>Fiddle

like image 51
Larnu Avatar answered Jun 16 '26 22:06

Larnu