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

mnowg1ta  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(274)

刚加入,需要帮助。我已经建立了一个消息传递系统的种类,我想附加读/未读的价值观,以整个线程/对话的人正在进行。为此,我有3个专门与线程相关的表: threads, posts, post_recipients ```
threads

  • id
  • user_id

posts
+id

  • title
  • text
  • thread_id
  • author

post_recipients

  • id
  • post_id
  • recipient_id
  • status
我找到了一种获取线程列表的方法,所以现在我要根据特定收件人查询每个线程的已读/未读邮件数。
这是我到目前为止写的,但是得到了一个错误“未知列(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;

9jyewag0

9jyewag01#

根据你的模式,没有 status 柱下 posts 但是有一个在下面 post_recipients .

1tu0hz3e

1tu0hz3e2#

你应该试着用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
...

相关问题