Mysql: sort result by column name

$qry="select * from table where category='car' or title='car' or description='car'"; 

but I want the output to display strings by category, then title, and then description.

**** Editing: I actually use a similar operator to search **

Example:

  id category title description 1 car 2 car 3 car 4 car 5 car 6 car 

is there any other way besides using the union?
Thank you in advance.

+5
source share
6 answers

You can do this using ORDER BY with the right keys. In MySQL, you can:

 ORDER BY (category = 'car') DESC, (title = 'car') DESC, (description = 'car') DESC 

MySQL treats logical expressions as integers in a numeric context, with 0 for false and 1 for true. Thus, DESC first installs the true versions.

You can also simplify the WHERE if you want:

 WHERE 'car' IN (category, title, description) 
+9
source

You can get this result using this operator:

 SELECT * FROM mytable WHERE (category='car' OR title='car' OR description='car') ORDER BY category = 'car' DESC, title = 'car' DESC, description = 'car' DESC 

How it works?

It will set the data order in DESC to sequentially , as indicated in the request. You can change the sequence as you wish.

+2
source

You can use ORDER BY for multiple columns, for example:

 SELECT * FROM tablename ORDER BY category DESC, title DESC, description DESC 

I tried this and it worked .

enter image description here

+1
source
 Try this , SELECT * FROM table where 'car' IN (category, title, description) ORDER BY category DESC, title DESC, description DESC 
+1
source

Your request may have multiple ORDER BY clauses.

  select *from table where category='car' or title='car' or description='car' ORDER BY category DESC, title DESC, description DESC 

See this answer for reference. mysql query order by multiple items

0
source

Try this query:

 select * from table where category='car' or title='car' or description='car' order by 1 desc, 2 desc, 3 desc 
0
source

Source: https://habr.com/ru/post/1240341/


All Articles