使用条件删除mysql中的重复记录

nfs0ujit  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(432)

我正在node.js上使用一个每秒运行一次的命令,它具有排除给定项的任何重复记录的功能,如示例中所示: AND t1.auction_id = 1335 .

DELETE FROM bid_account t1
WHERE t1.id < (Select max(t1.id) FROM bid_account t2 WHERE t1.bidding_price = t2.bidding_price) AND t1.auction_id = 1335;

我需要它来删除一个在 bidding_price 列,只保留一个。但重要的是,他并不是在整个表中进行搜索,而是像我在开始时通过列报告的那样搜索某个项目 auction_id .
我试图运行上述命令,但它返回以下错误:


# 1064 - You have a syntax error in your SQL next to 't1

WHERE t1.id < (Select max(t1.id) FROM bid_account t2 WHERE t1.bidding_price ' na linha 1

这个查询有什么问题?
我使用mysql数据库和表 bid_accountid 列作为索引和主列。
如果我使用下面的select,它通常会以重复的方式返回值。

SELECT bidding_price, count(*) FROM bid_account WHERE `auction_id` = 1335 GROUP BY bidding_price Having Count(*) > 1
sg3maiej

sg3maiej1#

您可以在sql查询中使用别名before from关键字删除行
例如
从测试t中删除t,其中t.id=3
因此,您的查询可以很好地从bid\u account t1中删除t1,其中t1.id<(从bid\u account t2中选择max(t1.id),其中t1.bidding\u price=t2.bidding\u price)和t1.auction\u id=1335;

lmyy7pcs

lmyy7pcs2#

你有两个来自mysql的怪癖。首先,在为表使用别名时,它需要遵循 DELETE . 所以,这就是你想要的:

DELETE ba FROM bid_account  ba
WHERE ba.id < (Select max(ba2.id)  -- I assume you want the max from the innter reference
               FROM bid_account ba2
               WHERE ba2.bidding_price = ba.bidding_price
              ) AND
      ba.auction_id = 1335;

但是,这仍然不起作用,因为您正在引用 bid_account 在table上。
所以,我想你想要更像这样的东西:

DELETE ba
    FROM bid_account ba JOIN
         (SELECT ba2.auction_id, ba2.bidding_price, MAX(ba2.id) as max_id  -- I assume you want the max from the innter reference
          FROM bid_account ba2
          WHERE ba2.auction_id = 1335
          GROUP BY ba2.auction_id, ba2.bidding_price
         ) ba2
         ON ba2.auction_id = ba.ba2.auction_id AND
            ba2.bidding_price = ba.bidding_price AND
            ba2.max_id > ba.id
WHERE ba.auction_id = 1335;

我还是觉得这没什么用。匹配行基于 bidding_price 似乎不寻常。我希望 auction_id 成为比赛的一部分。我怀疑你想 GROUP BY 以及 JOIN 两边都有 bidding_price 以及 auction_id .

相关问题