gpt4 book ai didi

mysql - 条件 SQL 选择 : when select has a value select all but the smallest date

转载 作者:行者123 更新时间:2023-11-29 06:55:00 25 4
gpt4 key购买 nike

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

如何选择来自用户 b@b.cn 且 userpk = 2 且 reg = 1 的所有订单,但只有来自 a@a.cn 的两个最新订单,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

不特定于单个用户的版本(如果您有超过 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

关于mysql - 条件 SQL 选择 : when select has a value select all but the smallest date,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13293426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com