php – MySQL查找行

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – MySQL查找行脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
让我们说100是一个开始,101是一个停止事件.这些应该交替,我想在他们不知道的时候找出它们.每次开始都应该有一个先前的停止事件.鉴于此表:
ID  EVENT_ID
10  100  // a start event
11  101  // a stop event
12   99  // some irrelevant event
13  100  // .. and so on:
14  101
15  100
16   99  // some irrelevant event
17  100  // <-- duplicate event: bad
18  100  // <-- duplicate event: bad again.
19  101

我遗漏了DATETIME专栏.

如何找到#15和#17,考虑到开始不应连续出现两次?
结果应采用以下形式:

EVENT_ID From_ID From_DATETIME    UPTO_ID UPTO_DATETIME
100      15      2014-01-01 14:00 17      2014-01-01 16:00

我想它可以像这样工作:
– 仅查找由DATETIME订购的事件100,101的子选择.
– 按EVENT_ID分组以使用count()查找重复项
..但我怀疑这可能会导致结果崩溃,因为组会忽略排序,
..并且我不知道如何获得两个(或更多!)相应的DATETIME值.

有可能在MysqL中找到它吗?我可以在PHP中处理这个问题,但我宁愿避免这种情况.

在我的示例中,所有行都具有相同的日期时间值.
DROP TABLE IF EXISTS T;
CREATE TABLE T
    (`ID` int auto_increment Primary key,`EVENT_ID` int,dt timestamp)
;

INSERT INTO T
    (`ID`,`EVENT_ID`)
VALUES
    (10,100),(11,101),(12,99),(13,(14,(15,(16,(17,(18,(19,101)
;

select id,event_id,dt as up_to_dt,PRevgood,prevdt as from_dt from
(
select 
T.*,if((@startstop = 100 and event_id = 101) or (@startstop = 101 and event_id = 100),'good','bad') as goodbad,@prevgood := if(if((@startstop = 100 and event_id = 101) or (@startstop = 101 and event_id = 100),'bad') = 'bad',@prevgood,id) as prevgood,@prevdt := if(if((@startstop = 100 and event_id = 101) or (@startstop = 101 and event_id = 100),@prevdt,dt) as prevdt,@startstop := event_id
from
T,(select @startstop:=101,@prevgood:=0,@prevdt:=0) VARs
where event_id in (100,101)
order by id
) sq 
where goodbad = 'bad';

返回

+----+----------+---------------------+----------+---------------------+
| id | event_id | up_to_dt            | prevgood | from_dt             |
+----+----------+---------------------+----------+---------------------+
| 17 |      100 | 2014-01-20 09:12:20 |       15 | 2014-01-20 09:12:20 |
| 18 |      100 | 2014-01-20 09:12:20 |       15 | 2014-01-20 09:12:20 |
+----+----------+---------------------+----------+---------------------+

脚本宝典总结

以上是脚本宝典为你收集整理的php – MySQL查找行全部内容,希望文章能够帮你解决php – MySQL查找行所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。