2017-10-10 53 views
-1

假設兩個表如下:如何模仿LIMIT 1在T-SQL

insert into tmp1 values(12345) // orderid 
insert into tmp1 values(54321) 
insert into tmp1 values(77777) 

insert into tmp2 values(12345, 1) // orderid, code 
insert into tmp2 values(12345, 2) 
insert into tmp2 values(54321, 1) 
insert into tmp2 values(77777, 1) 
insert into tmp2 values(77777, 2) 
insert into tmp2 values(77777, 3) 

,然後我寫了以下內容:

select a.orderid from tmp1 a 
inner join tmp2 b on b.orderid = a.orderid where b.code in (1,2) 

有沒有一種方法可以讓我剛上車的輸出:

12345, 
54321, 
77777 

這將是一個報告,我只想知道沒有複製的訂單號由於內部連接,雖然內部j oin很重要,因爲有多個代碼可供選擇。

+0

這不就是「DISTINCT」嗎? –

回答

0
SELECT DISTINCT a.orderid 
FROM tmp1 a 
     INNER JOIN tmp2 b 
       ON b.orderid = a.orderid 
WHERE b.code IN (1, 2) 
0
select distinct a.orderid from tmp1 a inner join tmp2 b 
on b.orderid = a.orderid where b.code in (1,2) 
+0

非常感謝。我一定非常厭倦忘記DISTINCT關鍵字。我不知道我的大腦在哪裏!感謝你把我帶回了陰間! – Coreysan

-1

您可以使用UNION操作這樣的 -

Select orderid from tmp1 
Union 
Select orderid from tmp2 Where code In (1,2); 

或者你也可以使用內部聯接與鮮明 -

SELECT 
    DISTINCT t1.Orderid 
FROM tmp1 t1 
INNER JOIN tmp2 t2 
ON t1.orderid = t2.orderid 
WHERE t2.code IN (1, 2); 
+0

聯合方法可以列出(1,2)中沒有b.code的orderids。每一個orderid都會被列出來。 –

-1

避免任何連接:

select distinct t2.orderid 
from temp2 t2 
where t2.code in (1,2) 

使用exists( 「半聯接」):

select t1.orderid 
from tmp1 t1 
    where exists (
    select null 
    from temp2 t2 
    where t1.orderid = t2.orderid and t2.code in (1,2) 
    ) 

使用窗口函數ROW_NUMBER():

select d.* from (
    select t2.orderid 
     , row_number() over(partition by t2.orderid order by t2.code) rn 
    from temp2 t2 
    where t2.code in (1,2) 
    ) d 
where d.rn = 1 

這第三個選項似乎矯枉過正,這個簡單的例子,但該技術是特別適用於查找諸如「第一」或「最後」或「最早」或「最新」等信息。