简体   繁体   English

mysql按字段名顺序包含在另一个表中的字段值

[英]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 我想这样订购,但不起作用: ORDER BY A.SortingFieldName

SortingFieldName will contain the name of the field, but not the value of that field in the Annonce table. SortingFieldName将包含字段的名称,但不包含Annonce表中该字段的值。

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. 为简单起见,我想按“类别”中配置的字段对Annonces行进行排序。

Like, if i have in Annonces : id,name,category_id,price_day,price_month 像,如果我在Annonces中:id,name,category_id,price_day,price_month

And in Categories : id,name,pricefield 并且在类别中: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. 我想根据类别的配置在Nononce中订购价格为price_month或price_day的行。

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. 用实际的字段名称替换field1field2等。

If you can't list all the possible field names, you'll have to write use dynamic SQL. 如果无法列出所有可能的字段名称,则必须使用动态SQL编写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM