【问题标题】:MySQL Deleting based upon a query resultMySQL 根据查询结果删除
【发布时间】:2017-01-01 22:19:17
【问题描述】:

我有以下 mysql 查询,它从我的数据库中的 pokemon 表中找到最近修改和唯一的 spawnpoint_id:

SELECT 
    t1.spawnpoint_id, t1.last_modified
FROM
    pokemon t1
        INNER JOIN
    (SELECT 
        MAX(last_modified) last_modified, spawnpoint_id
    FROM
        pokemon
    GROUP BY spawnpoint_id) t2 ON 
    t1.spawnpoint_id = t2.spawnpoint_id
    AND t1.last_modified = t2.last_modified;

我得到了我想要的结果...但是现在,我想删除所有匹配这些结果的记录。

我尝试将查询包含在 DELETE .. NOT IN 中,如下所示:

DELETE FROM pokemon WHERE (spawnpoint_id, last_modified) NOT IN (
SELECT 
    t1.spawnpoint_id, t1.last_modified
FROM
    pokemon t1
        INNER JOIN
    (SELECT 
        MAX(last_modified) last_modified, spawnpoint_id
    FROM
        pokemon
    GROUP BY spawnpoint_id) t2 ON 
    t1.spawnpoint_id = t2.spawnpoint_id
    AND t1.last_modified = t2.last_modified) x;

但我收到 MySQL 语法错误。我一直在寻找几个小时,最后希望这里的人可以帮助我发现我做错了什么。非常感谢。

编辑:显示创建表口袋妖怪;

CREATE TABLE pokemon ( encounter_id varchar(50) NOT NULL, spawnpoint_id varchar(255) NOT NULL, pokemon_id int(11) NOT NULL, latitude double NOT NULL, longitude double NOT NULL, disappear_time datetime NOT NULL, individual_attack int(11) DEFAULT NULL, individual_defense int(11) DEFAULT NULL, individual_stamina int(11) DEFAULT NULL, move_1 int(11) DEFAULT NULL, move_2 int(11) DEFAULT NULL, last_modified datetime DEFAULT NULL, time_detail int(11) NOT NULL, PRIMARY KEY (encounter_id), KEY pokemon_spawnpoint_id (spawnpoint_id), KEY pokemon_pokemon_id (pokemon_id), KEY pokemon_disappear_time (disappear_time), KEY pokemon_last_modified (last_modified), KEY pokemon_time_detail (time_detail), KEY pokemon_latitude_longitude (latitude,longitude) ) ENGINE=InnoDB DEFAULT CHARSET=utf8

【问题讨论】:

  • 请用实际错误更新帖子。
  • 查询很别扭。如果要从 table1 中删除 table2 中不存在的行,只需执行以下操作: DELETE FROM tablle1 WHERE (table1.spawnpoint_id, table1.last_modified) NOT IN ( SELECT table2.spawnpoint_id, table2.last_modified from table2)
  • 错误似乎是:“错误代码:1093。您不能在 FROM 子句中指定目标表 'pokemon' 进行更新” ...这就是为什么我认为添加 'x' 会解决那个。关于“尴尬”的查询,也许是这样。我想删除口袋妖怪表中具有不同'spawnpoint_id'除了最近的'last_modified'记录的所有记录......我可以按照我的描述选择那些记录,只是不知道最好的方法现在删除那些 不是 他们...

标签: mysql database sql-delete


【解决方案1】:

我认为问题在于您在子查询的 from 部分中使用了表 pokemon,您想从中删除行(这是不允许的)。

可以通过首先执行一个更新语句来标记要删除的行,然后执行一个单独的删除语句来解决这个问题。请注意,“不能在 from-part 中使用”-restriction 也适用于 update-statements。然而,这可以通过使用连接而不是子选择来解决,如下所示:

create table a (
  x int,
  y int
);

insert into a (x,y) values (1,2),(3,4);

update a a1, (select max(a2.x) as x from a a2) a3 set a1.y = 0 where a1.x = a3.x;

delete from a where y=0

【讨论】:

  • 斯蒂芬,谢谢。不幸的是,这个答案在我脑海中浮现。我喜欢标记要删除的行的想法(也许只是添加一个新列?)并使用类似的插入语句,然后执行删除......我会尝试。
猜你喜欢
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 2012-11-29
  • 2010-11-26
  • 1970-01-01
相关资源
最近更新 更多