[英]How to check a dates of a date range lies in between two dates in mysql query
[英]Check if a date lies between two dates from other table
我有两个表如下:
订阅:
user_id
started_at
ended_at
订阅表包含所有用户的历史成员资格。 从未订阅过的用户不会包含在此表中。 具有 X 个历史订阅的用户在表中将有 X 条记录。 对于用户最近的订阅,如果成员资格当前处于活动状态,则 colended_at 将为 null。
交易:
transaction_id (PK)
user_id
started_at
amount
该表跟踪每个历史交易的启动时间以及金额以及 user_id。
我们如何知道交易时对应的用户是否有活跃的金卡会员?
output 应该看起来像这样。
transaction_id
user_membership_active (bool)
我们如何检查 table1 中的日期是否位于另一个表中的两个日期之间? 任何帮助表示赞赏。
你期待这样的事情吗?
SELECT transaction_id,
CASE
WHEN ended_at IS NULL THEN 'True'
ELSE 'False'
END user_membership_active
FROM transactions t1
INNER JOIN subscriptions t2
ON t1.user_id = t2.user_id
AND t1.started_at BETWEEN t2.started_at AND
ISNULL(t2.ended_at, GETDATE())
根据您要显示的内容,我假设您仍会在事务表中插入一条记录,无论是否存在活动成员。
如果您想在插入交易记录后进行此检查 -
Select t.transaction_id,
case when t.started_at >= s.started_at
and t.started_at < NVL(s.ended_at, SYSDATE())
then 'Y' -- using Y/N for your boolean output
else 'N'
end as user_membership_active
from transactions t
inner join subscriptions s on t.user_id = s.user_id
如果我理解正确,您只需要一个标志。 一种方法使用exists
:
select t.*
(exists (select 1
from subscriptions s
where s.user_id = t.user_id and
s.started_at <= t.started_at and
(s.ended_at > t.started_at or s.ended_at is null
)
)
) as user_membership_active
from transactions t;
为了提高性能,您需要一个关于subscriptions(user_id, started_at, ended_at)
。
注意:如果一个人有多个并发订阅,这不会乘以结果集中的行数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.