Mysql 如何忽略下一个重复的行?
我需要你的帮助! 我有一张桌子:Mysql 如何忽略下一个重复的行?,mysql,sql,Mysql,Sql,我需要你的帮助! 我有一张桌子: CREATE TABLE `table` ( `id` int(11) NOT NULL AUTO_INCREMENT, `res` varchar(255) DEFAULT NULL, `value` int(6) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; -- Records of table INSERT
CREATE TABLE `table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`res` varchar(255) DEFAULT NULL,
`value` int(6) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
-- Records of table
INSERT INTO `table` VALUES (1, 'gold', 44);
INSERT INTO `table` VALUES (2, 'gold', 44);
INSERT INTO `table` VALUES (3, 'gold', 45);
INSERT INTO `table` VALUES (4, 'gold', 46);
INSERT INTO `table` VALUES (5, 'gold', 44);
INSERT INTO `table` VALUES (6, 'gold', 44);
INSERT INTO `table` VALUES (7, 'gold', 44);
INSERT INTO `table` VALUES (8, 'gold', 47);
我需要发出SELECT请求,该请求将忽略下一个或上一个重复的行,我收到如下数据:
- gold:44 (ignored 1 record)
- gold:45
- gold:46
- gold:44 (ignored 2 records)
- gold:47
复制记录不会忽略任何对象(第一个、第二个、最后一个)。
(我尝试使用group by value或distinct,但这样会删除具有相同值的其他记录)使用distinct子句选择唯一行,如下所示: 从
表格
您可以使用
间隙和孤岛解决方案解决此问题。
-通常这涉及到MySQL中不存在的ROW\u NUMBER()
-下面的解决方案模拟了带有变量的行号()
和按顺序
链接到示例:
如果我将res_ordinal
、val_ordinal
和res_ordinal-val_ordinal
添加到数据中,可以看出您现在可以区分这两组44
GROUP
INSERT INTO `table` VALUES ('1', 'gold', '44'); 1 - 1 = 0 (Gold, 44, 0)
INSERT INTO `table` VALUES ('2', 'gold', '44'); 2 - 2 = 0
INSERT INTO `table` VALUES ('3', 'gold', '45'); 3 - 1 = 2 (Gold, 45, 2)
INSERT INTO `table` VALUES ('4', 'gold', '46'); 4 - 1 = 3 (Gold, 46, 3)
INSERT INTO `table` VALUES ('5', 'gold', '44'); 5 - 3 = 2 (Gold, 44, 2)
INSERT INTO `table` VALUES ('6', 'gold', '44'); 6 - 4 = 2
INSERT INTO `table` VALUES ('7', 'gold', '44'); 7 - 5 = 2
INSERT INTO `table` VALUES ('8', 'gold', '47'); 8 - 1 = 7 (Gold, 47, 7)
注意:根据您的数据,我可以使用id
而不是制作我自己的resu_顺序
。然而,这样做可以解决id
序列中的漏洞,并拥有多个不同的资源。这意味着在下面的示例中,两个gold被认为是彼此的副本
1 Gold 44 1 - 1 = 0 (Gold, 44, 0)
2 Poop 45 1 - 1 = 0 (Poop, 45, 0)
3 Gold 44 2 - 2 = 0 (Gold, 44, 0) -- Duplicate
4 Gold 45 3 - 1 = 2 (Gold, 44, 2)
工作正常使用从表中选择不同的分辨率和值
。。。为避免冗余请注意,gold:44应该返回两次。嗯,刚刚返回了,我将尝试寻找答案。请展示您已经尝试过的内容…我不明白您为什么要这样做?唯一可行的方法是使用MySQL变量和/或创建滞后()或超前()函数类似于T-SQL,用于检查下一行和上一行是否需要在SQL中执行此操作?用一种能够按顺序工作并能处理循环的编程语言来完成这样的任务会更加容易和节省(参见MatBailie对您的解决方案的评论)-SQL@DieVeenman-更新为使用MySQL逻辑模拟行号(),感谢您发现:)在假设IDs中从不存在任何间隙的情况下有效。在关系数据库中,这是一个危险的假设;由于插入其他资源、插入失败、删除失败等原因,可能会出现间隙。这并不能提供问题的答案。若要评论或要求作者澄清,请在其帖子下方留下评论。“我需要提出选择性要求”好的,然后我误解了他
1 Gold 44 1 - 1 = 0 (Gold, 44, 0)
2 Poop 45 1 - 1 = 0 (Poop, 45, 0)
3 Gold 44 2 - 2 = 0 (Gold, 44, 0) -- Duplicate
4 Gold 45 3 - 1 = 2 (Gold, 44, 2)
select t1.*
from `table` t1
where not exists ( select 1
from `table` t2
where t1.id = 1+t2.id
and t1.res = t2.res
and t1.value = t2.value
);