简体   繁体   中英

MYSQL Null and empty values sorting

I have a table named users , and some of the columns are having null values which are user_country , user_state_user_city , user_area , user_pincode .

I want to sort the null values by count.

For example :

user_id user_country user_state user_city user_area user_pincode
  1       1            1           1         1         1              - all values
  2       1            1           1                   2              - 1 empty or null
  3       1                                            1              - 3 empty or null
  4       1            1           1                                  - 2 empty or null
  5       1                                                           - 4 empty or null

It should sorty by like below : Expecting output

user_id user_country user_state user_city user_area user_pincode
  2       1            1           1                   1            - 1 empty or null
  4       1            1           1                                - 2 empty or null
  3       1                                            1            - 3 empty or null
  5       1                                                         - 4 empty or null
  1       1            1           1         1         1            - all values

My code :

$where1 = "user_country IS NOT NULL  AND user_state IS NOT NULL AND user_city IS NOT NULL AND user_area_name IS NOT NULL AND user_area_pincode IS NOT NULL  AND user_country!='' AND user_state!='' AND user_city!='' AND user_area_name!='' AND user_area_pincode!=''";
                $this->db->where($where1);
$order = "user_city IS NOT NULL";
$this->db->order_by($order,'desc');

You could use this query:

SELECT yourtable.*
FROM yourtable
ORDER BY
  CONCAT(user_country,user_state,user_city,user_area,user_pincode) IS NOT NULL,
  (user_country IS NULL) +
  (user_state IS NULL) +
  (user_city IS NULL) +
  (user_area IS NULL) +
  (user_pincode IS NULL)

Please see fiddle here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM