Sort by "quantity (columns are not zero)"

I am looking for a way to sort MySQL results by the number of columns where the value is not null. Consequently,

[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 ignore the ID column, but in practice I don't care. The ID is always NOT NULL, so adding it to the counter will not change the results.

Does anyone have any ideas on this that don't involve parsing the PHP result into a new array? I am trying to save part of the processing at the DB level.

+2
mysql sql-order-by count order
source share
1 answer
 ORDER BY IF(`a` IS NULL, 0, 1) + IF(`b` IS NULL, 0, 1) ... DESC 

Where a , b , ... are the names of the fields (yes, you need to list them manually)

PS: if you do not know the difference between 0 and NULL as follows:

 ORDER BY `a` + `b` ... DESC 

will be enough for you

+4
source share

All Articles