0

I need to know if the last 5 entry's in a table were placed by the same userid (in the code below the user id is frozen_by.

Here's what I have

//count if the last 5 freezes was placed by the same user

$strFind="SELECT COUNT(*) AS `total` FROM `contest_frozen` WHERE `contest_id`=\"$pid\" AND `frozen_by`=\"$curmemid\" ORDER BY `id` DESC LIMIT 5";
$result=mysql_query($strFind) or die(mysql_error());
$row=mysql_fetch_array($result);
$freeze_total=$row['total'];

if($freeze_total>=5){
//do this
}

if($freeze_total<5){
//do this
}
4

1 回答 1

1

You could use a query like this: It returns the number of different users in the last 5 rows. It also returns the highest userid, so if UserCount == 1 and MaxUser == $curmemid then you know that that user places the last five records.

SELECT
  count(distinct frozen_by) as UserCount,
  max(frozen_by) as MaxUser
FROM 
  contest_frozen
WHERE 
  contest_id = $pid 
ORDER BY 
  `id` DESC 
LIMIT 5

If you need explicit counts, you can do that too. Query below returns the number of records by the given user and the number of records by other users. If ThisUserCount == 5 then all 5 records are from that user.

SELECT
  sum(case when frozen_by = $curmemid then 1 else 0 end) as ThisUserCount,
  sum(case when frozen_by = $curmemid then 0 else 1 end) as OtherUserCount

FROM 
  contest_frozen
WHERE 
  contest_id = $pid 
ORDER BY 
  `id` DESC 
LIMIT 5
于 2012-10-28T17:15:49.913 回答