Order by “count (columns not null)”

五迷三道 提交于 2019-12-08 02:55:50

问题


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 doesn'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.


回答1:


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



来源:https://stackoverflow.com/questions/5055540/order-by-count-columns-not-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!