我想删除表game
中的重复项。有些条目具有相同的playerId
和timeParameter
,而gameId
最低的条目应保留。
我可以用以下内容查询条目:
select a.`gameId` from `game` a
where not exists
(select min(b.`gameId`) as m from `game` b
group by b.`playerId`, b.`timeParameter`
having m = a.`gameId`);
但是我不能在delete语句中使用alis a :
delete from `game` a
where not exists
(select min(b.`gameId`) as m from `game` b
group by b.`playerId`, b.`timeParameter`
having m = a.`gameId`);
获取语法错误:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual
that corresponds to your MariaDB server version for the right syntax to use near 'a
where not exists
(select min(b.`gameId`) as m from `game` b
group by b.`' at line 1
此错误告诉我什么,但我知道我不能在删除语句中使用别名。
有解决方法吗?
答案 0 :(得分:1)
您可以创建子查询并创建一个派生表
delete from game where gameId IN
(
select gameId from(
select a.`gameId` from `game` a
where not exists
(select min(b.`gameId`) as m from `game` b
group by b.`playerId`, b.`timeParameter`
having m = a.`gameId`)
)tmp
)
答案 1 :(得分:1)
如果您使用的是别名,那么这是正确的,并且每个MySQL文档都必须在DELETE
语句中引用它。因此,请删除别名a
或将DELETE
语句设为
delete a from `game` a ...
注意
如果声明表的别名,则必须在何时使用别名 参考表格:
DELETE t1 FROM test AS t1, test2 WHERE ...
答案 2 :(得分:1)
使用@krishn patel idea创建一个临时表,这应该可行。
首先创建一个表 dontDeleteMe ,其中包含应保留的所有gameIds。
create table `dontDeleteMe` as
select min(`gameId`) as `theId` from `game`
group by `playerId`, `timeParameter`;
我可以将此表用于子查询:
delete from `game`
where `gameId` not in
(select `theId` from `dontDeleteMe`);
之后我可以删除临时表:
drop table `dontDeleteMe`;