2016-02-28 21 views
0

爲什麼此查詢不起作用?是不是因爲按順序組合?通過在MySQL中使用案例加入分組依據和排序

一個表與廣告,其他訂閱,第三個與服務,第四個是服務和位置之間的多對多關係(位置是廣告應該顯示的位置)。

我想是訂購存儲在廣告爲表位置2第一個廣告,那麼那些沒有位置定義,誰也再與位置1(產生這個順序programmicaly)

廣告表:
ID,名稱,subscription_id

訂閱表:
subscription_id,service_id爲,日期,支付等...

service_locations表:
service_id爲LOCATION_ID

,你可以本身有在這種情況下第四表,但它是不重要的


查詢:

select adverts.id, GROUP_CONCAT(service_locations.location_id) AS locations from adverts 
    left join subscriptions 
     on adverts.subscription_id = subscriptions.id 
    left join service_locations 
     on service_locations.service_id = subscriptions.service_id 
    group by adverts.id 
    order by case service_locations.location_id 
     when 2 then 1 
     when 1 then 3 
     else 2 
    end 


預期結果:

+----+-----------+ 
| id | locations | 
+----+-----------+ 
| 1 | 2   | 
| 3 | 1,2  | 
| 2 | null  | 
+----+-----------+ 


我真正得到(在連續第三次有位置2,但它被放置空後):

+----+-----------+ 
| id | locations | 
+----+-----------+ 
| 1 | 2   | 
| 2 | null  | 
| 3 | 1,2  | 
+----+-----------+ 

回答

0

當您在group by使用group by,所有列不應該有聚合函數。所以,我認爲你打算是這樣的:

select a.id, GROUP_CONCAT(sl.location_id) AS locations 
from adverts a left join 
    subscriptions s 
    on a.subscription_id = s.id left join 
    service_locations sl 
    on sl.service_id = s.service_id 
group by a.id 
order by max(case sl.location_id 
       when 2 then 1 
       when 1 then 3 
       else 2 
      end); 

我不知道,如果是max()你真正需要的,但你需要一個聚合函數。這尤其會產生在問題的輸出:

order by (case min(sl.location_id) 
       when 2 then 1 
       when 1 then 2 
       else 3 
      end); 
0

我已經必須組之前執行通過發現一種解決方案,命令,這不是默認behaivor,更多有關behaivour這裏:https://stackoverflow.com/a/14771322/4329156)(一個子查詢必須使用)

因此,查詢應該像

select *, GROUP_CONCAT(location_id) as locations from (
    select adverts.id AS id, service_locations.location_id AS location_id from adverts 
    left join subscriptions 
     on adverts.subscription_id = subscriptions.id 
    left join service_locations 
     on service_locations.service_id = subscriptions.service_id 
    order by case service_locations.location_id 
     when 2 then 1 
     when 1 then 3 
     else 2 
    end 
    ) as table 
    group by table.id 
    order by case table.location_id 
     when 2 then 1 
     when 1 then 3 
     else 2 
    end