以下是我的示例数据。第3行和第4行具有相同的st_case(主键),但它们的dist_min不同。我想保持行具有最小dist_min值。请注意,可能有超过2个重复行与同一个st_case关联。非常感谢你的帮助!
答案 0 :(得分:3)
在MySQL中,您可以使用delete
和join
:
delete s
from sample s left join
(select st_case, min(dist_min) as mindm
from sample s
group by st_case
) ss
on ss.st_case = s.st_case and s.dist_min > ss.mindm;
答案 1 :(得分:3)
你可以尝试这个:
DELETE t1 FROM table AS t1
LEFT JOIN table t2 ON t1.st_case = t2.st_case
WHERE t1.dist_min > t2.dist_min
答案 2 :(得分:2)
DELETE FROM sample
WHERE dist_min !=(SELECT dist_min FROM (SELECT * FROM sample) sample2
WHERE sample2.st_case = sample.st_case
ORDER BY dist_min
LIMIT 1)
答案 3 :(得分:2)
正如SAM M建议的那样,我不确定如何让具有相同主键的重复行。 但是,如果st_case不是您唯一的密钥,并且该表具有复合密钥 或者它是一个非关键专栏, 您可以编写一个触发器来控制插入 类似的东西:
CREATE table CALC_STATUS(id varchar(40), correlatoinToken integer, requirement double)
CREATE TRIGGER keep_min BEFORE INSERT ON CALC_STATUS
FOR EACH row
BEGIN
IF NEW.correlatoinToken = correlatoinToken AND NEW.requirement <= requirement then
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "A row with similar correlation token with lower requirement already exists";
ELSEIF NEW.correlatoinToken = correlatoinToken AND NEW.requirement > requirement
NEW.requirement = requirement;
END IF;
END;
SELECT c1.* FROM CALC_STATUS c1,(SELECT st_case,MIN(dist_min) FROM CALC_STATUS GROUP BY road_id) AS c2 WHERE c1.st_case=c2.st_case
答案 4 :(得分:1)
我没有测试这个,所以请原谅任何语法错误。 SQL ranking functions可以解决您的问题。基本上,您按一列分组,然后按另一列排名。然后你只能选择一级的那些。
SELECT *
FROM(
SELECT *, Rank() OVER (PARTITION BY 'st_case' Order by Dist_min DESC) as Rank
From 'tbl_Name')
WHERE Rank = '1'