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.

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

报告相同问题?

悬赏问题

  • ¥30 数字信号处理实验报告
  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程