2017-08-06 77 views
0

我確信這很簡單,但我真的很困難。這裏爲i從具有相同的結構和在這種情況下的數據或記錄僅返回匹配行SQL Server

表A

Ref cola colb id 
------------------ 
1  a  b 14 
1  a  b 24 

表B的兩個表想要的結果集的一個例子

Ref cola colb id 
------------------ 
1  a  b 1 
1  a  b 2 
1  a  b 3 

預期結果:

Ref cola colb id Ref1 cola1 colb1 id1 
---------------------------------------- 
1  a  b 14 1  a  b 1 
1  a  b 24 1  a  b 2 
+0

TableA中有兩行,而表B具有3行。爲什麼結果只包含2行? –

+0

它不一定必須是2行,它可以是3行,並且TableA中的第3行具有NULL值 – Muroiwa263

回答

2

用途:

SELECT * 
FROM table1 t1 
JOIN Table2 t2 
ON t1.Ref =t2.Ref AND t1.cola = t2.cola 
    AND t1.colb = t2.colb AND t1.id = t2.id 

SELECT * 
FROM table1 t1 
JOIN Table2 t2 
USING (Ref , cola , colb, id) 
1

另一種方式將是

;with cte 
as 
(
select Ref, cola, colb, id, 
hashbytes('sha1',concat(Ref, cola, colb)) as tb1hash 
from table1 
) 
select 
t1.Ref, --all required cols 
from cte c 
join 
(
select Ref, cola, colb, id, 
hashbytes('sha1',concat(Ref, cola, colb)) as tb2hash 
from table2 
) b 
on 
b.tb2hash=c.tb1hash 
+0

您應該至少在連接列之間添加分隔符以避免變形。 – lad2025

+0

@ lad2025:我認爲,這不會產生碰撞,因爲sha1會產生碰撞,所以花了很多年..「6,610年的處理器時間」https://www.theregister.co.uk/2017/02/23/google_first_sha1_collision/ – TheGameiswar

+0

我的意思是像'11 2'和'1 12'這樣的concat會產生相同的結果。在哪裏'11 | 2' <>'1 | 12' – lad2025

0

猜測:

;WITH TableAWithRowNum 
AS (
SELECT *, ROW_NUMBER(ORDER BY id) AS RowNum 
FROM dbo.TableA 
), TableBWithRowNum 
AS (
SELECT *, ROW_NUMBER(ORDER BY id) AS RowNum 
FROM dbo.TableB 
) 
SELECT a.*, b.* 
FROM TableAWithRowNum a 
INNER JOIN TableBWithRowNum b ON a.Ref = b.Ref 
--AND other join predicates on ColA, ... etc. 
AND a.RowNum = b.RowNum 
+0

爲了從兩個表中獲取所有行,而不是INNER JOIN,我會使用FULL OUTER JOIN。 –