简体   繁体   中英

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 .

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.

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.

[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.

SELECT 
    *
FROM
    users
WHERE
    state = 'active'
    AND retries < max_retries
    AND retries = (
        SELECT 
            MIN(retries)
        FROM
            users
        WHERE
            state = 'active'
            AND retries < max_retries
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM