在mysql查询中使用top删除dupliacte抛出错误代码

m4pnthwp  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(307)

我只是用top语法从表中删除了重复的值。但它返回错误代码。
查询:

DELETE top(SELECT COUNT(*)-1 FROM tests WHERE test_name='WALLET_01' AND product_id=25)FROM tests WHERE test_name='WALLET_01' And product_id=25;

错误代码:
错误代码:1064您的sql语法有错误;
在下面单独执行查询,返回int值为1:

SELECT COUNT(*)-1 FROM tests WHERE test_name='WALLET_01' AND product_id=25;

有人能帮我解释为什么我会有语法错误吗?

nhhxz33t

nhhxz33t1#

无法在top中使用子查询 Top 语法

[   
    TOP (expression) [PERCENT]  
    [ WITH TIES ]  
]

表达 Is the numeric expression that specifies the number of rows to be returned. expression is implicitly converted to a float value if PERCENT is specified; otherwise, it is converted to bigint. 我们可以看到它不支持子查询 TOP 仅限 expression 编辑
我看到你改变了dbms的用途。
mysql不支持 TOP 但你可以用 LIMIT 获取限制行。
如果没有 PK 在你的table上,你可以试着用 dynamic SQL 决定在运行时要删除多少行。
架构(mysql v5.6)

CREATE TABLE tests(
test_name VARCHAR(50),
product_id int
);

INSERT INTO tests VALUES('WALLET_01',25);
INSERT INTO tests VALUES('WALLET_01',25);

SET @sql = NULL;
SET @Rn = NULL;
SELECT
   (COUNT(*)-1) 
INTO @Rn
FROM tests
WHERE test_name='WALLET_01' AND product_id=25;

SET @sql = CONCAT('DELETE FROM tests WHERE test_name=''WALLET_01'' AND product_id=25 limit ',@Rn);

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

查询#1

SELECT * FROM tests;

| test_name | product_id |
| --------- | ---------- |
| WALLET_01 | 25         |

db fiddle视图

相关问题