需要一些关于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;
}
}
有没有办法在单个查询中执行此操作?
答案 0 :(得分: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
列保存了创建行的时间。
答案 1 :(得分: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";