Using LIMIT 1 in MySQL

后端 未结 5 2029
猫巷女王i
猫巷女王i 2021-02-01 02:54

When is it appropriate to add LIMIT 1 at the end of the query in MySQL. I normally add it in DELETE but I\'ve seen it being used with INSERT a and even UPDATE. Is it an overkill

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-01 03:46

     INSERT INTO .. VALUES () LIMIT 1
    

    Doesn't exist. Hopefully you know how many VALUES() you put in there!

     INSERT INTO .. SELECT ... LIMIT 1
    

    Does exist and is pretty useful, and off topic since the LIMIT is on the SELECT.

     DELETE ... LIMIT 1
     UPDATE ... LIMIT 1
    

    Extremely rarely useful. Either you know your database enough to be certain that your WHERE matches a UNIQUE condition, or you don't, in which case you should spend a little more time looking at your database and learning SQL.

    But ...

     UPDATE jobs SET owner=me WHERE owner IS NULL ORDER BY job_submit_time LIMIT 1
    

    Can be extremely useful! This makes a near-lockless job queue, where you can come and take a job from the queue without any waiting, locking, or conflict resolution. Quite excellent.

     DELETE FROM cache ORDER BY last_update_time LIMIT N
    

    Cache takes too much space ? Purge the N oldest rows...

提交回复
热议问题