2

I have a mysql table where a column can have NULL values. Can someone help me with a SQL to return all the rows with the column is null, and as well as the next non-null rows?

Eg:

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

SQL will return:

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

3 回答 3

1

I would suggest something like

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))

We return rows whos col2 is null, or if the col2 is null, we run a subquery to see if the row one before it (col1 - 1) has null in col2, if so we return that too.

于 2013-03-31T03:39:15.893 回答
1

Here's one way to do it using user defined variables:

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

SQL Fiddle Demo

于 2013-03-31T03:55:40.740 回答
1

Basing on your comment, update the answer. Actually for your case, you don't need any order by in the last, you need the native order of data I think. Probably I'm wrong, if so, please add order by as you need.

I borrow @sgeddes's solution, actually his solution fit your case best as far as I know. Only a tiny change is the second variable intialization, instead of NULL, give a non-null contanst value, then it can handle the first fews rows of data are not null scenario.


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

SQL FIDDLE DEMO

于 2013-03-31T04:49:55.073 回答