1

需要一些关于mysql的帮助。

我有一张满是出价的桌子,我需要检查是否有超过 3 个来自同一用户的出价一个接一个。

以下是一些代码示例:

$all = sql_get('select all bids from bids where auction_id = 1 order by amount asc');
$total = 0;

foreach ($all as $bid) {
  if ($bid->user_id == $user->id) {
    if (++$total <= 3) continue;
    $bid->burned = true;
    sql_store($bid);
    show_error('you cant have more than 4 bids one after another, the last bid was burned.');
  } else {
    $total = 0;
  }
}

有没有办法在单个查询中做到这一点?

4

2 回答 2

1
SELECT user_id, CASE WHEN @user_id = user_id 
    THEN @rownum := @rownum + 1 
    ELSE ((@user_id := user_id) * 0) + (@rownum := 1) END AS rownum
FROM (  SELECT user_id
        FROM bids, (SELECT @rownum := 0, @user_id := NULL) AS vars
        WHERE auction_id = 1
        ORDER BY created DESC) AS h
HAVING user_id = '{$user->id}' AND rownum >= 3

只需将 user_id 解析为查询,您就会知道是否连续 3 个。这假设您保存了使用列创建行的时间created

于 2013-02-11T12:29:30.353 回答
0

为什么不只做一个计数查询并在WHERE子句中传递 user_id 呢?

$query = "SELECT COUNT(bids) AS total_bids FROM bids WHERE auction_id = 1 AND user_id = '$user->id' ORDER BY amount";
于 2013-02-11T12:17:12.767 回答