在mysql group_concat字段中对筛选器进行排序

时间:2018-03-24 21:27:58

标签: mysql

我可以按颜色对mysql group_concat字段进行排序。但我无法按电机发动机功率排序。我能做些什么?颜色或引擎顺序?

SQL-FIDDLE-TABLE

select
ads.id,
ads.ad_title,
GROUP_CONCAT(DISTINCT ads_filter.filter_title SEPARATOR ','),
GROUP_CONCAT(DISTINCT ads_filter_option.filter_option SEPARATOR ',')
from ads
LEFT JOIN ads_filter_option
on find_in_set(ads_filter_option.id,ads.filter_option_id)
LEFT JOIN ads_filter
on ads_filter.id=ads_filter_option.filter_id
where cat_1 = 2
group by ads.id
order by GROUP_CONCAT(DISTINCT ads_filter_option.filter_option SEPARATOR ',')

预期结果:

White,2.0 Engine
White,2.0 Engine
Black,2.0 Engine
Black,2.0 Engine
Black,2.0 Engine
Black,2.0 Engine
Black,2.0 Engine
Black,1.6 Engine
Black,1.6 Engine
Black,1.6 Engine
Black,1.6 Engine
Black,1.6 Engine
Black,1.6 Engine
Black,1.6 Engine
Black,1.6 Engine
White,1.6 Engine
White,1.6 Engine

1 个答案:

答案 0 :(得分:1)

您可以先使用发动机功率对group_concat进行子查询,然后使用列别名进行排序。

For example:
select
id,
ad_title,
filter_title,
filter_option_color
from (
   select
   ads.id,
   ads.ad_title,
   GROUP_CONCAT(DISTINCT ads_filter.filter_title order by ads_filter.filter_title SEPARATOR ',') filter_title,
   GROUP_CONCAT(DISTINCT ads_filter_option.filter_option order by ads_filter_option.filter_option SEPARATOR ',') filter_option_power,
   GROUP_CONCAT(DISTINCT ads_filter_option.filter_option order by ads_filter_option.filter_option desc SEPARATOR ',') filter_option_color
   from ads
   LEFT JOIN ads_filter_option
   on find_in_set(ads_filter_option.id,ads.filter_option_id)
   LEFT JOIN ads_filter
   on ads_filter.id=ads_filter_option.filter_id
   where cat_1 = 2
       group by ads.id ) t
order by filter_title, filter_option_power desc;

Result:
id  ad_title                                        filter_title    filter_option
60  Motosiklet deneme reyonsiverek ilanı            Color,Engine    White,2.0 Engine
68  Elektrikli Araçlar deneme reyonsiverek ilanı    Color,Engine    White,2.0 Engine
59  Otomobil deneme reyonsiverek ilanı              Color,Engine    Black,2.0 Engine