Sort multiple text fields in MYSQL according to information entered or not
I have a expert table with fields like expert_description
, company_description
, expert_website
, expert_email
, company_website
.
These fields are not required, so they may be NULL
.
When searching the tables, entries with most non- NULL
fields should come first.
For example, there are four users:
The result should be
I suggest you to create a field in the user table that will store the count of fields filled.
This column should be updated every time the user adds/remove a field.
Then you simply can order by the "fieldcount" column.
use this query:
SELECT user FROM your_table
ORDER BY expert_description DESC, company_description DESC,
expert_website DESC, expert_email DESC, company_website DESC;
Thank you.
You can use something like this, if the values of your empty fields are NULL.
SELECT expert_description, company_description, expert_website, expert_email, company_website,
((expert_description IS NULL) + (company_description IS NULL) + (expert_website IS NULL) + (expert_email IS NULL) + (company_website IS NULL)) AS empty_count
FROM experts
WHERE 1
ORDER BY empty_count;
IS NULL will return 1
if the value of the field is NULL
else it will return 0
.
上一篇: 如何在多个用户中执行sql脚本(模式)