如何获取3表联接上特定列的计数?

时间:2018-10-05 00:45:16

标签: mysql database

非常新加入,需要一些帮助。我建立了各种消息传递系统,我想将已读/未读值附加到人们所拥有的整个线程/会话中。为此,我有3个表专门与线程相关:

threads, posts, post_recipients

threads
+ id
+ user_id

posts
+id
+ title
+ text
+ thread_id
+ author

post_recipients
+ id
+ post_id
+ recipient_id
+ status

我找到了一种获取线程列表的方法,因此现在我想针对每个线程查询基于特定收件人的已读/未读邮件数。

这是我到目前为止所写的内容,但收到一个错误消息“ unknown column(posts.status),所以我想我做的总和错误或联接:

select threads.id as thread, sum(posts.status = 1) as cnt 
from threads
left join (select thread_id, posts.user_id, status from posts left join post_recipients on posts.id = post_recipients.post_id) as posts on posts.thread_id = threads.id
where threads.id = 4;

2 个答案:

答案 0 :(得分:1)

根据您的架构,在status下没有posts列,但是在post_recipients下没有一列。

答案 1 :(得分:0)

您应该尝试使用CASE

SELECT threads.id AS thread,
SUM (CASE WHEN post.status = 1 THEN 1 ELSE 0 END) AS read,
SUM (CASE WHEN post.status = 0 THEN 1 ELSE 0 END) AS unread
...