2012-10-03 36 views
2

我有這樣的查詢:如何通過場GROUP ORDER BY

SELECT 
    t.type, 
    SUM(t.external_account) 
FROM 
    u_contracts c, 
    u_data u, 
    u_transactions t 
WHERE 
    c.user_id = u.id 
    AND t.contract_id = c.id 
    AND t.nulled =0 
    AND DATE (c.init_date) < DATE (u.dead) 
    AND u.dead IS NOT NULL 
    AND t.type != 'repay' 
GROUP BY 
    t.type; 

現在,這給了我想要的結果,但現在我想添加ORDER BY給它,但如特定字段名:

ORDER BY FIELD(t.type, 'type1', 'type2', ...) 

但我無法將其插入到查詢中。當我嘗試這樣的:

SELECT 
    t.type, 
    SUM(t.external_account) 
FROM 
    u_contracts c, 
    u_data u, 
    u_transactions t 
WHERE 
    c.user_id = u.id 
    AND t.contract_id = c.id 
    AND t.nulled =0 
    AND DATE (c.init_date) < DATE (u.dead) 
    AND u.dead IS NOT NULL 
    AND t.type != 'repay' 
ORDER BY 
    FIELD(t.type, 'initial', 'commision', 'overpay', 'penalty', 'penalty2') 
GROUP BY 
    t.type; 

它給我的SQL錯誤:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BY t.type' at line 17 

什麼是這樣做的正確方法?

+1

更改您的查詢到這一點:'選擇t.type,SUM(t.external_account)FROM u_contracts C,u_data U,u_transactions T,其中c.user_id = U。 ID和t.contract_id = c.id AND t.nulled = 0 AND DATE(c.init_date)

回答

8

你剛纔打錯爲了group byorder by;

... 
ORDER BY 
    FIELD(t.type, 'initial', 'commision', 'overpay', 'penalty', 'penalty2') 
GROUP BY 
    t.type; 

應該是:

... 
GROUP BY 
    t.type 
ORDER BY 
    FIELD(t.type, 'initial', 'commision', 'overpay', 'penalty', 'penalty2'); 
+0

笑,感謝M8,我知道有一些簡單的:) – Peon

+0

...和複選標記去???? – bobwienholt

+0

不得不等待,直到我可以接受的答案。 – Peon