1
通過提出疑難問題,使MySQL有一些樂趣。聚合函數無法按預期的方式與子查詢一起工作
從本質上講,我有滿滿一桌子的交易,並從我要確定出所有可用的產品(productid
),誰(userid
)買了最每一嗎? where子句中的類型是指交易類型,1表示購買。
我有一個子查詢,它自己返回一個爲每個人購買的總結產品列表,並且它本身運行良好。從這我試圖然後挑選最大的總和數量和產品,這是一個非常簡單的聚合。不幸的是它給了我有趣的結果! userid
與報告的最大銷售量不一致。
select
`userid`, `productid`, max(`sumqty`)
from
(select
`userid`, `productid`, sum(`qty`) as `sumqty`
from
`txarchive`
where
`type` = 1
group by `userid`,`productid`) as `t1`
group by `productid`
我已刪除了所有的內部聯接給予更多的口頭結果,因爲它們不改變這一切的邏輯。
如果您有興趣,這裏是tx
的結構。
id bigint(20) #transaction id
UserID bigint(20) #user id, links to another table.
ProductID bigint(20) #product id, links to another table.
DTG datetime #date and time of transaction
Price decimal(19,4) #price per unit for this transaction
QTY int(11) #QTY of products for this transaction
Type int(11) #transaction type, from purchase to payment etc.
info bigint(20) #information string id, links to another table.
*編輯 工作最終查詢:(其較大的)
select
`username`, `productname`, max(`sumqty`)
from
(select
concat(`users`.`firstname`, ' ', `users`.`lastname`) as `username`,
`products`.`name` as `productname`,
sum(`txarchive`.`qty`) as `sumqty`
from
`txarchive`
inner join `users` ON `txarchive`.`userid` = `users`.`id`
inner join `products` ON `txarchive`.`productid` = `products`.`id`
where
`type` = 1
group by `productname`,`username`
order by `productname`,`sumqty` DESC) as `t1`
group by `productname`
order by `sumqty` desc
嘿,這實際上工作。您添加的所有內容都是子查詢中的order by語句。不確定如何幫助,必須與MySQL的內部工作有關! – ArgGrr 2011-12-20 09:11:48
@ArgGrr:是的,它與MySQL(內部)如何工作'GROUP BY'有關。這就是爲什麼我也說這不是100%的交易(內部工作可能在未來版本中改變!)。我稍後會添加一個徹底的後續行動。 – 2011-12-20 14:00:39