B
B
Bogdan Khvalko2021-07-13 11:10:01
PHP
Bogdan Khvalko, 2021-07-13 11:10:01

How to sort different groups by different methods?

There is a table with categories. The category has a `parent_id` I need to get all the categories and sort them by `name` based on the value of `parent_id`.

If `parent_id` = 51 or 52 or 0 then `name` ASC otherwise `name` DESC.

I can solve this through CASE, but this solution seemed cumbersome to me, especially since there can be more categories. Is there an operator in sql like in_arra() PHP and can I somehow use it with IF. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2021-07-13
@oldzas

In SQL, sorting is SORT by direction, not by the value of the neighboring table. Make sorting on php or on what you then process the received data. There is an IN operator in SQL - maybe it will help you.

A
Akina, 2021-07-13
@Akina

ORDER BY CASE WHEN parent_id IN (0,51,52)
              THEN 1
              ELSE 2 
              END ASC,
         CASE WHEN parent_id IN (0,51,52)
              THEN name
              ELSE ''
              END ASC,
         CASE WHEN parent_id IN (0,51,52)
              THEN ''
              ELSE name
              END DESC

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question