在 MYSQL 中应用双重条件
Posted
技术标签:
【中文标题】在 MYSQL 中应用双重条件【英文标题】:Applying dual conditions in case when in MYSQL 【发布时间】:2015-06-22 12:06:56 【问题描述】:(问题已编辑)我的表有id,status,date,sequence
情况:获取满足的id:
date
是最大值,不超过今天的和 status
是A
如果超过 1 个状态具有相同的 date
,则只有当它具有最大 sequence
时才获取 id
我在dbVisulizer
中写mysql
。
编辑:尝试查询:
select id, max(date), max(sequence) from
table
where
table.date<=now() and status='A'
order by date desc,sequence desc
听起来我只是直接问问题而没有自己尝试任何事情,但是对于这种情况我完全卡住了,我尝试了case when
,但并没有真正取得任何好处,任何起点都是了解。
【问题讨论】:
发布您尝试过的任何内容,而不是发布需求。投票结束。 【参考方案1】:select id, max(date), max(sequence) from
table
where
table.date<=now() and status='A'
order by date desc,sequence desc
group_by id;
这应该会给你想要的结果。使表和字段名称适应您的表和字段。
【讨论】:
感谢 @Lelionow()
和 limit
不受支持(dbvisualizer 6.5.1),我猜您的查询会将结果限制为一条记录。休息看起来很有希望..不确定它是否正确
还需要group by
on id
,才能使用max
(聚合函数)
ehm...这不是您使用的工具的问题。语法与您使用的数据库引擎有关。 now() 和 limit 是 mysql 支持的,是基本功能。无论如何,您可以跳过限制 1 部分并将日期作为参数传递,而不是使用 noww
group_by 用于在 max.如果没有 sqlfiddle 或确切的表和数据结构,我只能给你一些关于如何达到你的观点的提示
收到错误id is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
【参考方案2】:
select id from
table
where
table.date<now() and table.status='A'
order by date desc,sequence desc
limit 1;
你应该自己检查它是否有错误。
【讨论】:
以上是关于在 MYSQL 中应用双重条件的主要内容,如果未能解决你的问题,请参考以下文章