0

我有三个 MYSQL 表

Requests -  request_id, request_msg, user_id, request_datetime
Responses - response_id, request_id, response_msg, user_id, response_datetime, readflag
Users-      user_id, user_email, user_name

readflag = 0 or 1

我想获取用户的所有请求,其中至少有 1 个响应未读此请求、总响应计数和此请求的未读响应计数。

4

2 回答 2

2

试试这个:

SELECT 
    a.request_id,
    COUNT(*) AS total_response_count,
    COUNT(b.request_id) AS unread_response_count
FROM
    Requests a
LEFT JOIN
    Responses b ON a.request_id = b.request_id AND b.readflag = 0
GROUP BY
    a.request_id
HAVING 
    COUNT(b.request_id) > 0

在这里,我们 LEFT JOIN 响应表的关系以及未读消息的位置 ( b.readflag = 0)。这使得所有具有读取响应的行都具有 NULL 值b.response_id。由于COUNT()在其计算中不考虑 NULL,我们只过滤具有至少 1 个未读响应 ( HAVING COUNT(b.request_id) > 0) 的请求。

因为我们 LEFT JOINed,所有响应都被保留,读取或未读......只是所有读取的行都将包含 NULL for b.request_idCOUNT(*)本质上依赖于一行的存在,所以这给了我们消息的总数。然后COUNT(b.request_id)给我们未读消息的计数,因为它仅将非 NULL 值纳入其计算。

于 2012-06-10T18:04:06.437 回答
0

尝试这样的事情:

SELECT COUNT(`res`.`response_id`) AS `total`, COUNT(`res`.`readflag`='0') AS `unread`
FROM `Requests` AS `req`
LEFT JOIN `Responses` AS `res` ON `req`.`request_id`=`res`.`request_id`
WHERE `unread`>1 AND `req`.`user_id`='[PLACE_USER_ID_HERE]'
于 2012-06-10T16:41:30.723 回答