简体   繁体   中英

mysql order by field name contained in another table field value

I have a search query where i need to order by a field contained in another table field value. Not very clear perhaps :)

Consider this :

        $requete = "
 SELECT A.*,
 (SELECT payspan FROM Categories WHERE id=A.category_id) AS SortingFieldName 
 FROM Annonces A 
 JOIN Categories C ON C.id=A.category_id
 WHERE A.deleted=0
 ORDER BY SortingFieldName";

I would like to order like this, but it does not work : ORDER BY A.SortingFieldName

SortingFieldName will contain the name of the field, but not the value of that field in the Annonce table.

How can i get the value of that field and then order by ?

I tried a variable, but dont seem to be able to use a variable inside a query ...

To make it simple, i would like to order Annonces lines by the field configured in Categories.

Like, if i have in Annonces : id,name,category_id,price_day,price_month

And in Categories : id,name,pricefield

I would like to order lines in Annonce with the value of price_month or price_day according to the configuration of the category.

Thx for any help.

Use this:

ORDER BY CASE SortingFieldName
            WHEN 'field1' THEN field1
            WHEN 'field2' THEN field2
            WHEN 'field3' THEN field3
            ...
         END

Replace field1 , field2 , etc. with the actual field names.

If you can't list all the possible field names, you'll have to write use dynamic SQL.

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