查看以下SQL小提琴:http://sqlfiddle.com/#!2/962496/1
如何从用户[email protected]中选择所有订单,其中userpk=2,reg=1
来自[email protected]的两个最新订单,userpk=1和reg=0。因此,查询将为userpk=2显示3个订单,但只有2个订单(不是userpk=1的最早订单2012-01-01
所以条件是reg,如果reg=0,那么忽略第一个顺序

最佳答案

我想这会给你你想要的结果:

select *
from users u
left join another a
  on u.userpk = a.uPK
where
(
  u.userpk = 2
  and u.reg = 1
)
or
(
  u.userpk = 1
  and u.reg = 0
  and a.odate not in (select min(odate)
                      from another a1
                      where u.userpk = a1.uPK)
)

SQL Fiddle with Demo
不是特定于单个用户的版本(如果您有两个以上的用户):
select *
from users u
left join another a
  on u.userpk = a.uPK
where
(
   u.reg = 1
)
or
(
  u.reg = 0
  and a.odate not in (select min(odate)
                      from another a1
                      where u.userpk = a1.uPK)
)

SQL Fiddle with Demo

10-04 19:06