SQL获取值,然后获取这些值的总数

时间:2018-03-20 21:50:56

标签: mysql sql

enter image description here 我正在制作一个拍卖脚本,其表格看起来像附图。

在拍卖中,两个用户可以设置相同的出价金额,例如,两个玩家可以设置出价为“1”的出价,这将使出价金额总计为两个。

我需要一个查询,该查询可以获取所有用户的单一出价金额以及该出价金额在拍卖ID范围内的总数。

目前我首先得到用户出价:

SELECT bid_amount FROM all_bids WHERE auction_id = '129' AND user_id = '9'

然后我循环遍历PHP中的每个数量并执行以下操作

SELECT COUNT(*) FROM all_bids WHERE auction_id = '129' AND bid_amount = 'xxx'

但这当然非常耗电,我相信它可以在一个查询中完成。

我到目前为止

SELECT bid_amount,COUNT(*) FROM (SELECT bid_amount FROM all_bids WHERE auction_id = '129' AND user_id ='9') as foo GROUP BY bid_amount

哪个返回了正确的出价金额,但计数都是 1 ,这是错误的,因为我猜我的错误查询只计算子查询中的值,而不是仅仅是用户放置的出价之外

2 个答案:

答案 0 :(得分:1)

 SELECT  a.*, b.cnt from all_bids a 
 join (select bid_amount,COUNT(*) cnt from all_bids group by bid_amount) b 
 on a.bid_amount=b.bid_amount
 WHERE a.auction_id = '123' AND a.player_id = '456'

答案 1 :(得分:0)

我想你想要Traceback (most recent call last): File "map.py", line 7, in <module> for sublist in id: TypeError: 'builtin_function_or_method' object is not iterable

group by

请注意,数字常量不需要单引号。

嗯。你可能想要这样的措辞:

select bid_amount, count(*)
from all_bids 
where auction_id = 123 and player_id = 456
group by bid_amount;