Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql SQL返回空行和对应的下一行_Mysql_Sql_Null - Fatal编程技术网

Mysql SQL返回空行和对应的下一行

Mysql SQL返回空行和对应的下一行,mysql,sql,null,Mysql,Sql,Null,我有一个mysql表,其中一列可以有空值。有人能帮我用SQL返回列为null的所有行以及下一个非null行吗 例如: SQL将返回: row 1, NULL row 2, foo 1 row 4, NULL row 5, foo 3 row 8, NULL row 9, foo 6 我会建议像这样的东西 select * from table t1 where t1.col2 = null or (t1.col2 != null and exists (select 1 from table

我有一个mysql表,其中一列可以有空值。有人能帮我用SQL返回列为null的所有行以及下一个非null行吗

例如:

SQL将返回:

row 1, NULL
row 2, foo 1
row 4, NULL
row 5, foo 3
row 8, NULL
row 9, foo 6

我会建议像这样的东西

select * from table t1
where t1.col2 = null
or (t1.col2 != null and exists (select 1 from table t2 where t1.col1 - 1 = t2.col1 and t2.col2 = null))

我们返回col2为null的行,或者如果col2为null,我们运行子查询以查看它前面的行(col1-1)在col2中是否为null,如果是这样,我们也会返回该行。

这里有一种使用用户定义变量的方法:

select col1, col2 
from (
  select *,
    @showRow:=IF(@prevCol2 is NULL,1,0) showRow,
    @prevCol2:=col2
  from yourtable
    join (SELECT @showRow:= 0, @prevCol2:= NULL) t
  ) t
where showRow = 1 or col2 is null
order by col1, col2

根据您的评论,更新答案。实际上,对于你的例子,你不需要任何顺序,在最后,你需要的是数据的本机顺序。可能我错了,如果是这样,请根据需要添加订单

我借用了斯盖德斯的解决方案,实际上据我所知,他的解决方案最适合你的情况。只有一个微小的变化是第二个变量初始化,而不是NULL,给出一个非NULL的contanst值,那么它就可以处理第一个fews行数据不为NULL的场景


select col1, col2 
from (
  select *,
    @showRow:=IF(@prevCol2 is NULL,1,0) showRow,
    @prevCol2:=col2
  from yourtable
    join (SELECT @showRow:= 0, @prevCol2:= 'foo') t
  ) t
where showRow = 1 or col2 is null

如果多个连续行有空值怎么办?这只在col1有连续整数且没有缺失值的情况下才有效。@Dan Bracuk这确实是真的,我希望我的答案足够明确。这与我一个多小时前发布的答案不完全相同吗?哦,对不起,请验证您的查询,它已经可以处理连续的空场景(+1)。是的,几乎一样。嗨,ljh,谢谢你。我在开头又添加了几行,它们不是空的,但SQL会返回它们。我希望结果从第一个空行开始。如果我删除了“join(SELECT\@rownumber:=0)t”,那么它就可以工作了。你能解释一下为什么我需要“join(SELECT\@rownumber:=0)t”吗?实际上,在你的情况下,你并不真的需要这个join,没有join它会更好地为你服务。我稍微更新一下@sgedes的解决方案,它也可以为您服务,他的想法很好。

select col1, col2 
from (
  select *,
    @showRow:=IF(@prevCol2 is NULL,1,0) showRow,
    @prevCol2:=col2
  from yourtable
    join (SELECT @showRow:= 0, @prevCol2:= 'foo') t
  ) t
where showRow = 1 or col2 is null