如何在T-SQL中模仿LIMIT 1

时间:2017-10-10 00:20:42

标签: sql-server

假设两个表具有以下内容:

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

这是一个报告,我只想知道由于内部联接而没有复制的订单号,尽管内部联接很重要,因为可以选择多个代码。

4 个答案:

答案 0 :(得分:0)

SELECT DISTINCT a.orderid 
FROM   tmp1 a 
       INNER JOIN tmp2 b 
               ON b.orderid = a.orderid 
WHERE  b.code IN ( 1, 2 ) 

答案 1 :(得分:0)

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

答案 2 :(得分:-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);

答案 3 :(得分:-1)

避免任何加入:

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

使用存在(“半连接”):

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

对于这个简单的例子,这第三个选项似乎有些过分,但该技术对于查找诸如“第一”或“最后”或“最早”或“最新”等信息特别有用。