How to sort the result of a query by a column where there is a value in another column in the same table?

Asked

Viewed 150 times

0

I have a table with several columns, and I want to sort the results by the values of one column where another column in the same table is equal to a value.

I have tried implementing the query with CASE, IF's and FIELD().

I want the results sorted by tech.value to be displayed when tech.id_color = 5

Here is the query:

SELECT DISTINCT * 
FROM products, tech_products 
WHERE products.idsub = 1 AND 
    tech_products.id = products.id 
ORDER by tech.id_cor = 5 AND tech.value ASC
  • Only want to sort when it’s tech.id_color = 5? Or just want results where tech.id_color = 5?

  • @Marcelovieira I want to sort by tech.id_cor = 5. But by the way it is done for the way to show the results where tech.id_cor = 5?

  • I don’t know the structure of your bank, but I believe you want something like this: SELECT DISTINCT * FROM products, tech_products, tech WHERE products.idsub = 1 AND tech_products.idProduct = products.id AND tech.idProduct = products.id AND tech.id_cor = 5 ORDER by tech.value ASC

  • It did not work, the intended is to have an ORDER BY tech.value when tech.id_color = 5.

1 answer

1


SELECT DISTINCT * 
FROM products, tech_products 
WHERE products.idsub = 1 AND 
    tech_products.id = products.id 
ORDER by (case when (tech.id_cor = 5) then 0 else 1 end) ASC,
         tech.id_cor

The syntax of CASE poe vary according to BD , but I believe it solves.

  • No, tech,value is not Boolean. It is a specific value/number.

  • I edited the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.