我需要使用以下条件排除bidding_price
列中的重复记录:
表:bid_account
要检查的栏目:
id
= PRIMARY KEY
auction_id
=每件商品的ID
bidding_price
=插入值(必须检查每个产品的重复性)
bid_flag
=必须始终等于以下值:' d'
bidding_type
=必须始终等于:: &的值#39; S'
在bidding_price
列中始终存在相同的记录,它不能具有相同的记录,具有相同的产品ID(auction_id
)。
它不应该具有的示例:
auction_id |的 bidding_price
------ 10 ------------ 0.02
------ 10 ------------ 0.02
------ 11 ------------ 0.02
------ 11 ------------ 0.02
正确的是:
auction_id |的 bidding_price
------ 10 ------------ 0.02
------ 11 ------------ 0.02
我尝试使用以下命令:
DELETE ba
FROM bid_account ba JOIN
(SELECT ba2.auction_id, ba2.bidding_price, MAX(ba2.id) as max_id
FROM bid_account ba2
WHERE ba2.bid_flag = 'd' AND ba2.bidding_type = 's'
GROUP BY ba2.auction_id, ba2.bidding_price
) ba2
ON ba2.auction_id = ba.auction_id AND
ba2.bidding_price = ba.bidding_price AND
ba2.max_id < ba.id
WHERE ba.bid_flag = 'd' AND ba.bidding_type = 's' AND ba.auction_id = ba2.auction_id
问题是它删除了多条不应删除的记录,没有正确进行验证。我该怎么办?
答案 0 :(得分:1)
ID是您表中的 PRIMARY KEY ,因此您可以MAX(id)
成为您的
预订ID,然后使用NOT IN
按ID删除MAX(id)
你可以试试这个。
DELETE ba FROM bid_account ba
WHERE ba.id NOT IN
(
SELECT max_id FROM
(
SELECT auction_id, bidding_price, MAX(id) max_id
FROM bid_account
WHERE bid_flag = 'd' AND bidding_type = 's'
GROUP BY auction_id, bidding_price
) t
)
sqlfiddle:http://sqlfiddle.com/#!9/0f2e5/1
修改强>
如果您想获得最低价值的ID,可以在where子句的子查询中使用MIN(id)
DELETE ba FROM bid_account ba
WHERE ba.id NOT IN
(
SELECT min_id FROM
(
SELECT auction_id, bidding_price, MIN(id) min_id
FROM bid_account
WHERE bid_flag = 'd' AND bidding_type = 's'
GROUP BY auction_id, bidding_price
) t
)
sqlfiddle:http://sqlfiddle.com/#!9/ffe92/1
答案 1 :(得分:0)
以下声明应该为您提供所需的所有记录。
SELECT ba2.auction_id, ba2.bidding_price, MAX(ba2.id) as max_id
FROM bid_account ba2
WHERE ba2.bid_flag = 'd' AND ba2.bidding_type = 's'
GROUP BY ba2.auction_id, ba2.bidding_price;
not-in子句应该为您提供您不需要的所有记录。 因此,从不在id中的bid_account中删除(#sub查询以获取所需的ID#)和ba.bid_flag =&#39; d&#39;和ba.bidding_type =&#39; s&#39;应该删除重复的记录。
答案 2 :(得分:0)
您可以使用PRIMARY KEY:ID删除它。 它用于唯一标识删除操作的记录。 请参阅此处的演示:http://sqlfiddle.com/#!9/603d56/1
它使用在子查询中选择ID(选择它两次将避免错误:无法指定目标表进行更新)。子查询与您的查询类似,它选择将保留的ID。使用NOT IN意味着删除子查询中不等于这些ID的其余行。
delete e.*
from bid_account e
where e.id not in (
select id from (
select a.id
from bid_account a
join bid_account b
on a.auction_id=b.auction_id
and a.bidding_price=b.bidding_price
and a.bid_flag=b.bid_flag
and a.bidding_type=b.bidding_type
where a.bid_flag='d' and a.bidding_type='s'
and a.id < b.id) tt);