PHP MySQL查询 - 仅显示行

时间:2017-08-05 04:33:38

标签: php mysqli

我有一张类似于此的表

id    message    state        timestamp
1     abcd       Heartbeat    1970-01-01 01:00
2     efgh       Start        1970-01-01 02:00
3     sdcvsd     Stop         1970-01-01 02:30
4     efgh       Start        1970-01-01 03:00
5     sdcvsd     Stop         1970-01-01 03:30
6     dsdfsd     Heartbeat    1970-01-01 04:10
7     sdcsc      Heartbeat    1970-01-01 04:20
8     sewwdf     Heartbeat    1970-01-01 04:30

我想要做的是在PHP中查询此表并显示行,但只显示Heartbeat的最新行,因为它非常重复,我只需要知道最后一行是什么时候发生的。所有其他国家即使重复也会回应。因此输出将是(最新的):

8 sewwdf     Heartbeat    1970-01-01 04:30
5 sdcvsd     Stop         1970-01-01 03:30
4 efgh       Start        1970-01-01 03:00
3 sdcvsd     Stop         1970-01-01 02:30
2 efgh       Start        1970-01-01 02:00

我只能用

将其遗漏
mysqli_query($con, " SELECT * FROM msg WHERE state <> 'Heartbeat' ORDER BY id DESC LIMIT 16 " );

我认为我不能将GROUP BYDISTINCT用于多个州。

如何在不影响其他状态的情况下仅查询最新的Heartbeat状态,或者在PHP回显中删除较旧的状态?

5 个答案:

答案 0 :(得分:2)

这也有效:

select * from
`msg`
where
`state` = 'Heartbeat'
and
`id` =  
(
select
`id`
from
`msg`
where
`state` = 'Heartbeat'
order by `timestamp` desc
limit 1
)

union

select * from
`msg`
where
`state` <> 'Heartbeat'

order by `timestamp` desc

答案 1 :(得分:0)

试试这个:

mysqli_query($con, "SELECT * FROM msg GROUP BY(state) ORDER BY id DESC LIMIT 16" );

答案 2 :(得分:0)

enter image description here

您的查询是:

mysqli_query($con, " SELECT * FROM msg WHERE state <> 'Heartbeat' ORDER BY id DESC LIMIT 16 " );

我认为应该是:

mysqli_query($con, " SELECT * FROM msg WHERE state="Heartbeat" ORDER BY id DESC LIMIT 16 " );

你可以看到我的附图,他们发生了什么?谢谢。

答案 3 :(得分:0)

尝试此查询:

SELECT * FROM `msg` GROUP BY `state` ORDER BY `id` DESC,`Timestamp` DESC LIMIT 16 

它会起作用

答案 4 :(得分:0)

你也可以尝试这个

select * from `test2` where `state` != 'Heartbeat' OR `id` = (select `id` from `test2` where `state` = 'Heartbeat' order by `date` desc limit 1 )

如果需要订购日期

select * from `test2` where `state` != 'Heartbeat' OR `id` = (select `id` from `test2` where `state` = 'Heartbeat' order by `date` desc limit 1 ) ORDER BY date DESC