PHP / MySQL - 每个用户在1个表中共计2个不同的总计

时间:2014-08-21 21:16:23

标签: php mysql count

我无法理解这一个!所以我正在寻求帮助......

对于每个用户,我都试图对分配给他们的帖子类型求和。

用户表:crm_users 列:users_id,users_first,users_last

帖子表:crm_entities 列:crm_id,users_id,settype,post

我想COUNT()用户的总帖子,其中settype = draft以及settype = published,例如:

Name------------Published---------Drafts
John Smith---------15---------------3
Nancy Grace--------11-------------  5
Jay Martin----------7--------------14

我相信我这让它变得比它可能更难......或者至少我认为!

感谢您的任何建议!

2 个答案:

答案 0 :(得分:0)

因为MySQL使用1代表true而0代表false,所以你可以使用:

SELECT
    u.users_first,
    u.users_last,
    SUM(p.settype='published') as Published,
    SUM(p.settype='draft') as Drafts
FROM
    crem_users u
LEFT JOIN
    crm_entities p
ON
    u.users_id = p.users_id
GROUP BY
    u.users_id
ORDER BY Published DESC;

答案 1 :(得分:0)

尝试:

select u.users_first, (select count(*) as qty from crm_entities e where e.settype='draft' and e.users_id = u.users_id) drafts, (select count(*) as qty from crm_entities e where e.settype='published' and e.users_id = u.users_id) published from crm_users u