I have a database of users where they can send messages to other users (up to four) and the ID of the message they sent is in their user row.
Name | Email | Msg1 | Msg2 | Msg3 | Msg4
--------+-------------+------+------+------+-----
Pez | me@me.com | 1 | 55 | 42 | 5
Steve | fake@me.com | 0 | 0 | 0 | 0
Leon | josh@me.com | 3 | 0 | 3 | 5
How in a MySQL query can I get the amount of those message rows that are not empty or not equal to 0, allowing me to order by that? So it would return
Pez | 4 Mesasges
Leon | 3 Messages
Steve | 0 Messages
Im my mind something like:
order by count(!empty(msg1)+!empty(msg2)+!empty(msg3)+!empty(msg4))
With normalized tables it could be as simple as
But with your schema try something like
edit: Vincent Ramdhanie’s answer using if() doesn’t rely on MySQL’s behaviour to use 0 as false and 1 as true as result of a comparison. I would prefer that.