dqqfuth6736 2013-09-05 04:17
浏览 48
已采纳

在单个查询中获取文件夹名称和总读取/未读取

My SQL database structure is as follows...

email_folders

id, name

email_messages

id, id_folder, date, date_read

In a single MySQL query I'm trying to get the folder names, their total email messages count both email total count and unread count per folder.

Thus far I have the basic counting bit down though the returned array in PHP returns the number of rows that there are emails for and undesirably does not return all the folders from the folders from the email_folders table.

Here is what I currently have...

SELECT 
ef.name, 
(SELECT count(id) FROM email_messages WHERE id_folder=ef.id AND date_read<date) AS unread, 
(SELECT count(id) FROM email_messages WHERE id_folder=ef.id) AS total 
FROM email_messages AS em
LEFT JOIN email_folders AS ef ON ef.id=em.id_folder;

There are currently four folders though over a hundred rows are returned so I know I'm doing something wrong. I'll be happy to make any necessary clarifications.

  • 写回答

1条回答 默认 最新

  • dtpt75860 2013-09-05 04:32
    关注
    select
        f.name FolderName,
        count(m.id) TotalMessagesCount,
        sum(m.date_read < m.date) TotalUnreadMessagesCount
    from email_folders f
    left join email_messages m on f.id = m.id_folder
    group by f.id
    

    I really wonder why date_read < date means Unread for you. Having the date_read set to null makes more sense to me be considered as Unread.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题