mysql - 如何对mysql中的值进行多次检查

标签 mysql sql

这是我的 table

enter image description here

假设:

..如果 ID 的最后一个有效条目是 1,那么就可以了

..如果 ID 的最后一个有效条目为 0,则表示检查有效值为 1 的前一个条目

..如果 ID 的最后一个有效条目为空,那么它就毫无用处

现在我想做的是

  1. 获取该 ID 的最后一个条目的有效值为 1 的 ID

  2. 如果 ID 的最后一个条目的有效值为 0,则它将采用有效值为 1 之前的条目。

  3. 如果某个 id 的最后一个条目的“有效”为 0,但其上方的值为 null,则结果中完全避免该 id

不,这就是我想要达到的结果

enter image description here

那么如何完成这个任务。

如何为此编写sql。

提前致谢。

最佳答案

我认为你可以用蛮力方法来处理这个问题。即从最后两行获取 novalid 信息,并在 where 子句中使用该信息:

select id, no, valid
from (select t.*,
             (select t2.no
              from t t2
              where t2.id = t.id
              order by t2.no desc
              limit 1
             ) as last_no,
             (select t2.valid
              from t t2
              where t2.id = t.id
              order by t2.no desc
              limit 1
             ) as last_valid,
             (select t2.no
              from t t2
              where t2.id = t.id
              order by t2.no desc
              limit 1, 1
             ) as last_no_2,    
             (select t2.valid
              from t t2
              where t2.id = t.id
              order by t2.no desc
              limit 1, 1
             ) as last_valid_2      
      from t
     ) t
where (last_valid = 1 and no = last_no) or
      (last_valid = 0 and last_valid_2 = 1 and no = last_no_2)

关于mysql - 如何对mysql中的值进行多次检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55755773/

相关文章:

mysql - SQL:如何使用 2 个不同的条件进行查询?

php - 如何对两个以上的表使用连接?

mysql - 即使在相关表中找不到相关记录,也可以从一个表中检索所有记录

mysql - 为什么这个带有 DATE 的 SQL 查询不起作用?

c# - 如何检查表中是否存在值,如果存在则删除它?

sql - 在 SQL Server 2008R2 中使用 CAST 函数除以 2 个数字

mysql - Laravel 5.5 - 迁移不起作用

php - 无法加入两个外键

php - mySQL/PHP 实际发生了什么类型的错误

java - datetime 和 tinyint 的数据类型查询