gpt4 book ai didi

mysql - 在 MYSQL 查询中使用 TOP 删除重复项会引发错误代码

转载 作者:行者123 更新时间:2023-11-29 16:58:18 25 4
gpt4 key购买 nike

我刚刚使用 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;

错误代码:

Error Code: 1064 You have an error in your SQL syntax;

单独执行下面的查询返回int值为1:

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

任何人都可以帮助我为什么我会收到语法错误?

最佳答案

您无法在 Top 中使用子查询

顶级语法

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

expression

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中的子查询,仅表达式

<小时/>

编辑

我看到你改变了你使用的dbms。

Mysql不支持TOP,但可以使用LIMIT获取限制行。

如果您的表中没有PK,您可以尝试使用动态SQL get来决定要在运行时删除多少行。

架构 (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 |
<小时/>

View on DB Fiddle

关于mysql - 在 MYSQL 查询中使用 TOP 删除重复项会引发错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52419761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com