简体   繁体   English

MySQL检查从最后到开始的条件是否为真,如果停止则返回

[英]MySQL check if a condition is true from last to start and if stopped return

I really love to know how this is possible without doing a for loop.My way is lame,I check the last then take the previous check again and add this values to an array and when the condition wasn't true anymore I return the array.This is not pure sql and uses php for loop so it's not very performant,I need to do this with sql.Example:我真的很想知道在不进行 for 循环的情况下这是如何实现的。我的方式很蹩脚,我检查最后一个然后再次进行前一个检查并将这些值添加到数组中,当条件不再为真时,我返回数组。这不是纯 sql 并且使用 php for 循环,所以它的性能不是很好,我需要用 sql.Example 做到这一点:

chatTable:
from_id    to_id     msg                  time
2          1         Hi                   2 days ago(as timestamp)
1          2         Hello                yesterday
1          2         How you doing?       today

So here we are going to take all the messages that id 1 sent from the latest until It's not him anymore.所以在这里我们将把 id 1 从最新发送的所有消息都取出来,直到它不再是他。

1->2 How you doing  = (true)
1->2 Hello  = (true)
2->1 Hi = (false)

so所以

return
1->2 How you doing
1->2 Hello

First way is to order the recrods in desc order of timestamp.第一种方法是按时间戳降序排列记录。 Then look for patterns in your data such that the next_from_id is same as that of the current_from_id.然后在您的数据中查找模式,使 next_from_id 与 current_from_id 相同。 If they are different then ignore.如果它们不同,则忽略。

If this looks correct the following can be done如果这看起来正确,则可以执行以下操作

select * from (
    select from_id
           ,to_id
           ,timestamp
           ,lead(from_id) over(order by timestamp desc) as next_frm_id
      from chatTable
      )x
 where x.from_id = x.next_frm_id

If I understand correctly, you want the last set of messages that are for from_id = 1 .如果我理解正确,您需要最后一组来自from_id = 1的消息。 That would be:那将是:

select ct.*
from chatTable ct
where ct.from_id = 1 and
      ct.timestamp > (select max(ct2.timestamp)
                      from chatTable ct2
                      where ct2.from_id <> 1
                     );

This assumes that the most recent message if from id 1.这假设最新的消息来自 id 1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM