duancha1065 2014-04-30 14:54
浏览 9

仅允许1行时删除最后插入的行SQL

I was wondering why my delete was not functioning.

I am trying to DELETE SQL row, the last SQL row inserted when only 1 row with an ip address and a user id is accepted and only one row with an ip address and a blank user id is accepted.

Here is my code:

DELETE
FROM visitor
WHERE ip_address NOT IN
    (SELECT ip_address
     FROM visitor
     WHERE ip_address = '".$ipAddress."'
         AND user_id = ''
     ORDER BY user_id DESC LIMIT 1)

Why is my SQL row not DELETING?

  • 写回答

1条回答 默认 最新

  • doucheng9058 2014-04-30 15:01
    关注

    Simple: because it's not allowed to use the table from which to delete in the sub-query. Just run the SELECT query separatly, and use the result to perform the DELETE...

    RTM, it clearly states this is not allowed here:

    Incorrectly used table in subquery:
    
    Error 1093 (ER_UPDATE_TABLE_USED)
    SQLSTATE = HY000
    Message = "You can't specify target table 'x'
    for update in FROM clause"
    This error occurs in cases such as the following, which attempts to modify a table and select from the same table in the subquery:
    
    UPDATE t1 SET column2 = (SELECT MAX(column1) FROM t1);
    
    You can use a subquery for assignment within an UPDATE statement because subqueries are legal in UPDATE and DELETE statements as well as in SELECT statements. However, you cannot use the same table (in this case, table t1) for both the subquery FROM clause and the update target.
    

    Particularly the last sentence is important: However, you cannot use the same table (in this case, table t1) for both the subquery FROM clause and the update target.

    There is a hacky way around this, it's silly but it worked last time I checked, which is to wrap your sub-query in another sub (WHERE x IN (SELECT id FROM (SELECT id FROM tbl...))). But that's just awful in every way

    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制