1

我有以下功能

function availableChatRoom($topic_id){
$max_rooms = 2;
$max_users = 2;

$sqli = "SELECT COUNT(DISTINCT room_num) AS numRooms FROM forum_chat WHERE topic_id = '$topic_id'";
$num_rooms = queryColumnVal($sqli, "numRooms");

$sqlii = "SELECT room_num, COUNT(user_id) AS numUsers FROM forum_chat 
          WHERE topic_id = '$topic_id' AND (status = 'online' AND status = 'offline') AND chat_msg = ''
          GROUP BY room_num
          HAVING numUsers < $max_users ORDER BY msg_date";

$num_rooms_with_spaces = mysqlNumRows($sqlii, "room_num");
queryColumnVal($sqlii, "room_num");

if($num_rooms == 0){
    return 1;
}
elseif($num_rooms <= $max_rooms){

    if($num_rooms_with_spaces == 0){
        return $num_rooms + 1;
    }
    else{
        return queryColumnVal($sqlii, "room_num");
    }
}
else{
    return "none";
}   

}

这个想法是让函数返回一个带空格的聊天室号码。- 每次用户加入房间时,都会插入一条没有消息的行,状态为在线 - 每次用户离开房间时,都会插入一条没有消息的行,状态为离线 我现在正在尝试编写一个函数来检查是否有每个主题的任何备用房间 想法是选择已登录但未注销的用户数小于每个房间的最大聊天数的 room_num。有人可以帮我处理我的 $sqlii。

谢谢

4

3 回答 3

3

在SELECTHAVING clause之前评估- 所以服务器还不知道该别名。

SELECT room_num, COUNT(user_id) AS numUsers 
FROM forum_chat 
WHERE topic_id = '$topic_id' AND 
      (status = 'online' OR status = 'offline') AND 
      chat_msg = ''
GROUP BY room_num
HAVING COUNT(user_id) < $max_users ORDER BY msg_date
  1. 首先形成中所有表的乘积from clause
  2. 然后where clause评估 以消除不满足 search_condition 的行。
  3. Next, the rows are grouped using the columns in the group by clause.
  4. Then, Groups that do not satisfy the search_condition in the having clause are eliminated.
  5. Next, the expressions in the select clause target list are evaluated.
  6. If the distinct keyword in present in the select clause, duplicate rows are now eliminated.
  7. The union is taken after each sub-select is evaluated. 8.Finally, the resulting rows are sorted according to the columns specified in the order by clause.
于 2012-05-25T11:32:47.607 回答
1

您的查询中有几个错误:

  • (status = 'online' AND status = 'offline')

这断言您的查询现在根本不会返回。使用:(status = 'online' OR status = 'offline')或等效的(status IN ('online', 'offline'))

  • COUNT(user_id)

这不计算在线减去离线用户的差异。纠正逻辑。

  • ORDER BY msg_date

在查询中,在, or子句GROUP BY中使用非聚合列是不好的,尽管 MySQL 允许这样做。除非该列依赖于分组表达式。由于显然不依赖于,因此您应该将其替换为聚合函数:HAVINGSELECTORDER BYmsg_dateroom_num

ORDER BY MAX(msg_date) 或者 ORDER BY MIN(msg_date)


$sqlii = "
   SELECT room_num, 
          COUNT(CASE WHEN status = 'online' THEN 1 END) 
            - COUNT(CASE WHEN status = 'offline' THEN 1 END) 
          AS numUsers 
   FROM forum_chat 
   WHERE topic_id = '$topic_id' 
     AND status IN ('online', 'offline')
     AND chat_msg = ''
   GROUP BY room_num
   HAVING COUNT(CASE WHEN status = 'online' THEN 1 END) 
          - COUNT(CASE WHEN status = 'offline' THEN 1 END) 
          < $max_users 
   ORDER BY MAX(msg_date)
     ";
于 2012-05-25T11:31:42.733 回答
0

您不能HAVING在同一SELECT级别中使用列的别名。那是因为在你的 MySQLONLY_FULL_GROUP_BY会被激活。

试试这个 -

HAVING COUNT(user_id) < $max_users ORDER BY msg_date
于 2012-05-25T11:19:16.493 回答