Need a SQL query statement for this case

时间:2015-10-29 15:45:06

标签: mysql sql

This is the structure of the table

mysql> select * from p1;
+----------+-------+-----------+
| username | token | last_used |
+----------+-------+-----------+
| a        | aacs  |         5 |
| d        | dddd  |         3 |
| a        | aaaaa |         3 |
+----------+-------+-----------+

How can I delete the record who has the minimum last_used value from the set queried by username? In this case ,the given username parameter is 'a',then I shold delete the record 'a','aaaaa',3 because 3 is smaller than 5(the username of last_used(5) is 'a',too).

My answer is

delete from persistent_logins 
where last_used=(select * 
                 from (select MIN(last_used) 
                       from persistent_logins where username=?)as t
                 ) 
  and username=?

but it's useful,I need a statement like delete .... from..where username=? It is important that only one parameter is allowed.But my answer has two parameter.

1 个答案:

答案 0 :(得分:1)

You can actually use ORDER BY and LIMIT with DELETE. The rows will be deleted in that order with LIMIT controlling how many are deleted.

If the ORDER BY clause is specified, the rows are deleted in the order that is specified. The LIMIT clause places a limit on the number of rows that can be deleted.

(From: https://dev.mysql.com/doc/refman/5.0/en/delete.html)

Try something like this:

DELETE FROM p1
WHERE username = ?
ORDER BY last_used ASC
LIMIT 1