在条件下删除MYSQL中的重复记录

时间:2018-04-14 21:17:18

标签: mysql sql

我正在使用在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

2 个答案:

答案 0 :(得分:0)

你有两个来自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

所以,我认为你想要更像这样的东西:

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 BYJOIN上的bidding_priceauction_id

答案 1 :(得分:0)

您可以在sql query

中的from keyword之前使用别名删除行

例如

从t测试t中删除t,其中t.id = 3

所以你的查询工作正常 从bid_account t1删除t1 在哪里t1.id&lt; (选择max(t1.id)FROM bid_account t2 WHERE t1.bidding_price = t2.bidding_price)AND t1.auction_id = 1335;