我有下表:
邮件
默认情况下,deleted
列包含值0000-00-00 00:00:00
当某些内容被删除时,deleted
列将设置为删除日期。例如:2017-08-14 09:37:13
现在,我想查询此表格,如果没有用户记录user_id
,请获取deleted
= 0000-00-00 00:00:00
的{{1}}记录或最新的deleted
值{1}} = deleted
答案 0 :(得分:1)
您可以使用案例对特定值进行排序:
select user_id
from YourTable
order by
case
when deleted = '0000-00-00 00:00:00' then '9999-12-31 23:59:59'
else deleted
end desc
limit 1
其中'9999-12-31 23:59:59'
是maximum value of a datetime。
对于多个用户,您可以通过联接查找最大值:
select *
from Mails m1
join (
select user_id
, max(
case
when deleted = '0000-00-00 00:00:00' then '9999-12-31 23:59:59'
else deleted
end) max_deleted
from Mails
group by
user_ud
) m2
on m1.user_id = m2.user_id
and case
when m1.deleted = '0000-00-00 00:00:00' then '9999-12-31 23:59:59'
else m1.deleted
end = m2.max_deleted
答案 1 :(得分:0)
稍微修改Andomar的答案,取消限制,你可以尝试类似的事情:
SELECT user_id
FROM YourTable
WHERE
case
when deleted = '0000-00-00 00:00:00' then 'true'
else deleted then 'true'
end desc = 'true'
当Case语句按顺序运行时,如果删除的日期为&00; 00:00:00'来自WHERE子句,则会尝试为过滤器返回true。如果这是假的,它将移动到下一个始终保持尝试并通过过滤器的情况。
虽然不是最漂亮的。