繁体   English   中英

根据来自另一个表的ID对字段值进行计数来计算另一个表的行数

[英]Counting number of rows from other table with field value based on ids selected from another table

我有以下表格:

conversation_folder {
    conversation_folder_id,
    user_id
    ...
}

conversation_user {
    conversation_id
    owner_user_id
    is_unread
}

conversation_folder_relations {
    conversation_id
    conversation_folder_id
    user_id
}

我想选择记录出的conversation_folder表,但是我想包括有未读,对特定的文件夹中的会话数量user_idowner_user_idconversation_user表)。

一个查询是否可行,还是我必须先获取文件夹,然后运行另一个查询才能获取未读计数?

编辑:

为了增加明显性,此查询提供了所需的结果,但是它涉及多个子查询,这与理想情况相去甚远:

SELECT conversation_folder.*,
(
    SELECT COUNT(conversation_id)
    FROM conversation_user
    WHERE conversation_id IN (
            SELECT conversation_id
            FROM conversation_folder_relations
            WHERE conversation_folder_relations.user_id = conversation_user.owner_user_id
                AND conversation_folder_id = conversation_folder.conversation_folder_id
            )
        AND is_unread = 1
    ) AS unread_count
FROM conversation_folder
WHERE conversation_folder.user_id = ?

最好分别查询两者。 也可以通过联接user_id和owner_user_id列,然后对结果表进行计数来解决。 但是,在SqlServer上使用不佳时,联接的性能极差,这也许与MySql不同。 由于我仅使用SqlServer,因此未经测试。

SELECT count(conversation_id)
FROM conversation_user
INNER JOIN conversation_folder_relations
ON conversation_user.owner_user_id = conversation_folder_relations.user_id;

http://www.w3schools.com/sql/sql_join_inner.asp

 SELECT conversation_folder_id, count(conversation_id)
 FROM conversation_user  cu
 JOIN conversation_folder_relations cfr
   ON cu.conversation_id = cfr.conversation_id
 WHERE 
     cu.owner_user_id = @user_id
 AND is_unread = true
 GROUP BY conversation_folder_id

对于您的模型, @user_id必须在所有@user_id中。 否则,您将需要LEFT JOIN但是您的问题没有说明。

我假设您为每个用户创建了session_id,并在每次创建新对话时将is_unread设置为true。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM