面试求解, MYSQL 下如何找到相同的记录并仅保留一个?

2018-03-28 16:19:02 +08:00
 jahan

表结构 from to amount date time label from 是起点 to 是终点 amount 是产品量,date 是发生日期,time 是发生时间,label 是动作方向( 1 代表 from 到 to,2 代表 to 到 from )。 表里记录例如,

      from to  amount   date       time label
item1  A    B    22    20180302   120808   1
item2  A    C    1     20180402   101001   2
itme3  B    A    22    20180302   120810   2

这样认定 item1 和 item3 是相同的,然后删掉 label 位 2 的, 比如在一天 date 的同一个时间 time+/2 分钟内,如果 from 和 to 的内容相反,label 不同则判断为 ji'l 记录相同。选一个删除。 上面的例子为样,认定 item1 和 item3 是相同的,然后删掉 label 位 2 的。

如何用 mysql 的函数实现?

4122 次点击
所在节点    MySQL
9 条回复
sculley
2018-03-28 17:25:30 +08:00
select a.* from a join a as b where a.`date`=b.`date` and a.`from`=b.`to` and a.`to`=b.`from` and a.id>b.id;
breadenglish
2018-03-28 17:29:38 +08:00
提示:自己关联自己
a.from=b.to AND a.to=b.from AND a.label<b.label AND ABS(a.time-b.time)<=2
weics
2018-03-28 17:34:43 +08:00
SELECT
a.*
FROM
a
JOIN b
WHERE
a.date = b.date
AND a.from = b.to
AND a.to = b.from
AND a.label > b.label
AND ABS(a.time - b.time) <= 2
AND a.label = 2
qinrui
2018-03-28 17:36:06 +08:00
delete from table c
where
c.item in
(
select a.item
from table a,table b
where
a.from=b.to
and a.to=b.from
and a.amount=b.amount
and a.time-b.time<2
and a.time-b.time>-2
and a.label <> b.label
and a.label=2
)
rensuperk
2018-03-28 17:49:01 +08:00
DELETE FROM item
WHERE id IN (SELECT a.id
FROM (SELECT
i1.*,
if(i1.time >= i2.time, i1.time, NULL) max_time
FROM item i1 LEFT JOIN item i2
ON i1.amount = i2.amount AND i1.date = i2.date AND abs(i1.time - i1.time) < 2 AND i1.id != i2.id
AND
((i1.`from` = i2.`from` AND i1.`to` = i2.`to` AND i1.label = i2.label) OR
(i1.`from` = i2.`to` AND i1.`to` = i2.`from` AND
i1.label != i2.label))
WHERE i2.id IS NOT NULL
HAVING max_time IS NOT NULL
ORDER BY i1.id) a)


求 offer
rensuperk
2018-03-28 17:59:12 +08:00
还可以改进一下,不用求最大时间为空,添加条件 i1.time>i2.time 就行了
xrlin
2018-03-28 18:02:26 +08:00
可以用变量进行记录,这样就不需要用 join 了
jahan
2018-03-28 19:06:37 +08:00
@sculley
@xrlin
@rensuperk
@rensuperk
@qinrui
@weics
@breadenglish
太棒了。话说是不是并没有一个函数来实现这个需求?
jahan
2018-03-29 10:04:15 +08:00
mysql 函数还真是挺少的。minus,except 都不支持哈,这个里面 time_to _sec,timediff,str_to_date 都要用到了。

后面还有一个题目是如何追踪交易的,一直也没想出什么好办法。感觉交易追踪要考虑的太多了。

from to amount balance date time label
A B 22 3 20180302 120808 1
A C 1 5 20180402 101001 2
B A 22 22 20180302 120810 2
C D 1 5 20180402 101002 2
D M 23 2 20180403 090812 2
B C 15 22 20180302 120809 1
B D 7 0 20180303 090808 1


给定一个点 A 或者其他,如何检索出其交易路径呢?比如 A 给 B 了 22 个物品,b 给了 C 15 个( B )给了 D7 个。这样追踪下去,但是要确保最初的都是 a 的 22 个。

这个怎么完成呢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/442174

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX