我目前正在开发拍卖系统,功能全部完成。我现在需要在用户的个人资料中添加一个计数,该计数显示用户当前正在出价的项目数。
系统由两个关键表组成(当然系统中有额外的表格,但这些是与此问题相关的唯一表格):
item_sales
+-----+------------------+------------+-------------+---------+
| id | selling_format | duration | list_date | buyer |
+-----+------------------+------------+-------------+---------+
item_sales_bids
+-----+-------------+-----------+---------------+-----------+--------+
| id | sale_item | user_id | current_bid | max_bid | date |
+-----+-------------+-----------+---------------+-----------+--------+
item_sales_bids
。date
是出价时间的Unix时间戳。
我可以轻松获得给定用户使用以下查询进行的所有出价的计数:
SELECT COUNT(DISTINCT(`item_sales_bids`.`user_id`)) AS `total`,
SUM((`sale`.`list_date` + (`sale`.`duration` * 86400)) - UNIX_TIMESTAMP()) AS `endTime`
FROM `item_sales_bids`
INNER JOIN `item_sales` `sale` ON `item_sales_bids`.`sale_item` = `sale`.`id`
WHERE `user_id` = 1
GROUP BY `sale_item`
HAVING `endTime` > 0
我想做的是运行类似于上述的查询,但仅包括指定用户是当前最高出价者的记录(即给定项目的出价集的最大ID条目具有{{1} } value =我们的用户)。
不幸的是,我对如何实现这一目标感到茫然。
我已经设置了一个SQLFiddle来协助> http://sqlfiddle.com/#!2/b98e4/3
答案 0 :(得分:2)
执行子查询以获取所有项目的最新出价,然后将其加入item_sales_bids以仅处理最新项目。
这样的事情: -
SELECT COUNT(DISTINCT(item_sales_bids.user_id)) AS total,
SUM((sale.list_date + (sale.duration * 86400)) - UNIX_TIMESTAMP()) AS endTime
FROM item_sales_bids
INNER JOIN item_sales sale ON item_sales_bids.sale_item = sale.id
INNER JOIN
(
SELECT sale_item, MAX(id) AS LatestBid
FROM item_sales_bids
GROUP BY sale_item
) Sub1
ON item_sales_bids.sale_item = Sub1.sale_item AND item_sales_bids.id = Sub1.LatestBid
WHERE user_id = 1
GROUP BY item_sales_bids.sale_item
HAVING endTime > 0
答案 1 :(得分:0)
这应该可以解决问题。在用户1和用户之间切换2将显示所需的行为。在示例数据中,用户1不返回任何数据(他们不是高出价者),用户2返回单行,当前高出价为50。
SELECT COUNT(DISTINCT(`bids`.`user_id`)) AS `total`,
`highbids`.`sale_item`,
`highbids`.`maxBid`,
SUM((`sale`.`list_date` + (`sale`.`duration` * 86400)) - UNIX_TIMESTAMP()) AS `endTime`
FROM `item_sales_bids` `bids`
INNER JOIN `item_sales` `sale` ON `bids`.`sale_item` = `sale`.`id`
INNER JOIN (SELECT MAX(`current_bid`) AS `maxBid`, `sale_item`, `user_id`
FROM `item_sales_bids`
GROUP BY `sale_item`, `user_id`
ORDER BY `current_bid` DESC LIMIT 1,1)
AS `highbids` ON `bids`.`user_id` = `highbids`.`user_id`
WHERE `bids`.`user_id` = 2
GROUP BY `bids`.`sale_item`
HAVING `endTime` > 0