[英]How to write a WHERE clause that uses the MIN() value of a column in the same the table?
I need to write a query with the following logic:我需要使用以下逻辑编写查询:
Get all rows that have state
= "active", that have retries
< max_retries
, and (from those qualifying rows) only return the rows with the least retries
.获取所有具有state
= "active" 的行,具有retries
< max_retries
,并且(从那些符合条件的行中)只返回retries
最少的行。
I have this query:我有这个查询:
SELECT *
FROM users
WHERE state = 'active'
AND retries < max_retries
AND retries = (SELECT MIN(retries) FROM users);
my table:我的表:
+-----------------------------------------+
| id uid retries max_retries state |
+-----------------------------------------+
| 1 Jack 3 5 active |
| 2 Jill 1 3 active |
| 3 John 3 3 active |
| 4 James 0 5 no |
| 5 Jim 2 7 no |
+-----------------------------------------+
In this case, my query should return the row containing Jill
because Jill has: state = active, retries < max_retries and the smallest number of retries.在这种情况下,我的查询应该返回包含Jill
的行,因为 Jill 具有:state = active、retries < max_retries 和最小重试次数。
However, my attempts always get some incorrect results.但是,我的尝试总是得到一些不正确的结果。 I looked at self join and union etc, but I can't seem to figure out how to solve it.我看着 self join 和 union 等,但我似乎无法弄清楚如何解决它。
[EDIT]: I think I figured it out now, but could someone please confirm it? [编辑]:我想我现在想通了,但有人可以确认一下吗?
SELECT *
FROM users
WHERE state = 'active'
AND retries =(SELECT MIN(retries) FROM users WHERE retries < max_retries )
After adding the state
and max_enteies
conditions to the main query and the subquery, I am now achieving the expected results.在主查询和子查询中添加state
和max_enteies
条件后,我现在达到了预期的结果。
SELECT
*
FROM
users
WHERE
state = 'active'
AND retries < max_retries
AND retries = (
SELECT
MIN(retries)
FROM
users
WHERE
state = 'active'
AND retries < max_retries
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.