有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java选择和删除

我想选择表中的第一行,按time(升序)排序,然后删除该行。我不想使用两个查询,因为有可能另一个客户端会在删除该行之前选择该行(将有多台计算机同时从不同的网络连接)

我在想我能做点什么

SELECT * FROM `mytable` ORDER BY `time` LIMIT 1;
    DELETE FROM `mytable` ORDER BY `time` LIMIT 1

。。。但我有一个错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '; DELETE * FROM pending ORDER BY time LIMIT 1' at line 1

最好的方法是什么?谢谢


共 (3) 个答案

  1. # 1 楼答案

    您可以使用子查询,如

    delete from table where id in ( select id from table order by time limit 1);
    

    就性能而言,我不确定这个解决方案有多好。你可能需要做一个分析,看看这对你是如何起作用的

  2. # 2 楼答案

    您必须创建一个临时表,MySQL不允许您从正在使用的表中删除,请参见以下代码:

    insert  tmpTable
            (id)
    select  id
    from    YourTable yt
    order by time limit 1;
    
    delete  
    from    YourTable
    where   ID in (select id from tmpTable);
    
  3. # 3 楼答案

    关于您的错误消息(与您的问题不同):

    DELETE * FROM pending ORDER BY time LIMIT 1
    

    看起来你的语法有错误。尝试删除*。就是

    DELETE FROM pending ORDER BY time LIMIT 1
    

    应该可以