2012-07-12 82 views
3

我有這個疑問:顯示ROWNUM問題的MySQL

SET @row_num = 0; 
SELECT 
(SELECT @row_num := @row_num + 1) AS itempurchase_code, 
(SELECT supplier_code FROM qa_items_purchases a WHERE a.item_invoicecodesupplier = b.item_invoicecodesupplier GROUP BY supplier_code ORDER BY COUNT(*) DESC LIMIT 1) AS supplier_code, 
(SELECT user_code FROM qa_items_purchases a WHERE a.item_invoicecodesupplier = b.item_invoicecodesupplier GROUP BY user_code ORDER BY COUNT(*) DESC LIMIT 1) AS user_code, 
22 AS status_code, 
item_invoicecodesupplier AS item_invoicecodesupplier, 
(SELECT itempurchase_date FROM qa_items_purchases a WHERE a.item_invoicecodesupplier = b.item_invoicecodesupplier GROUP BY itempurchase_date ORDER BY COUNT(*) DESC LIMIT 1) AS itempurchase_date 
FROM qa_items_purchases b 
GROUP BY (item_invoicecodesupplier) 
ORDER BY itempurchase_code; 

我得到這樣的結果: enter image description here

如果你看看有沒有(2itempurchase_code列,我能做些什麼來顯示數字按順序?

回答

3

如果查詢包含GROUP BY,則必須在外部查詢中添加行號。

SET @row_num = 0; 
SELECT (SELECT @row_num := @row_num + 1) AS itempurchase_code, * 
FROM 
(
    SELECT ... -- your original query goes here 
) AS T1 
ORDER BY itempurchase_code 
+0

非常感謝您的回答解決我的問題 – 2012-07-12 20:55:26

+0

@JohnNuñez:我忘了提,你應該有ORDER BY的外部查詢。 – 2012-07-12 20:57:23