条件SQL选择:当select有一个值时,选择除最小日期之外的所有日期

时间:2012-11-08 16:35:43

标签: mysql sql

查看以下SQL小提琴:http://sqlfiddle.com/#!2/962496/1

如何选择来自用户b@b.cn的所有订单,其中userpk = 2且reg = 1但仅限 来自a@a.cn的两个最近订单,其中userpk = 1且reg = 0.因此查询将显示3个订单,用于userpk = 2但只有2个订单(不是最早的订单2012-01-01来自userpk = 1 < / p>

所以条件是reg,如果reg = 0则忽略第一个订单

1 个答案:

答案 0 :(得分:2)

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

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

不是针对单个用户的版本(如果您有超过2个用户):

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