Order by "count (columns not null)"
I'm looking at a way to order the MySQL results by a count of the columns where the value is not null. Therefore,
[id] [1] [1] [0] [1] [1] = 4
[id] [0] [1] [1] [1] [0] = 3
[id] [0] [0] [0] [1] [1] = 2
[id] [1] [0] [0] [0] [0] = 1
In the above case I'm ignoring the ID column but in practice I wouldn't care. ID is always NOT NULL so adding it to count wouldn't change the results.
Anyone have any idea on this that d开发者_如何学Gooesn't involve doing a PHP parse on the result into a new array? I'm trying to keep the processing portion in the DB level.
ORDER BY IF(`a` IS NULL, 0, 1) + IF(`b` IS NULL, 0, 1) ... DESC
Where a
, b
, ... is the names of fields (yes, you need to enumerate them all manually)
PS: if you don't know the difference between 0
and NULL
this:
ORDER BY `a` + `b` ... DESC
will be good enough for you
精彩评论