sql:查询两个独立的表并返回计数值,然后按两个返回值分组

ibps3vxo  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(324)

我正在努力把这个问题弄对。我得到了返回的表来显示昵称和两个相关的值。这些表是:用户(昵称、姓名等)postsauth(昵称、posted等)postcomm(昵称、comid等)
如果numposts&numcomments中返回的两个值都为null(也就是说,如果它们没有评论或创建一个post),我试图让它不包含用户。我不知道该怎么做。代码如下

SELECT u.nickname, pa.numPosts, pc.numComments
FROM Users u
LEFT JOIN
(SELECT pa.nickname, COUNT(pa.nickname) AS numPosts
    FROM postAuthors pa
    GROUP BY pa.nickname
)pa
ON u.nickname = pa.nickname LEFT JOIN 
(SELECT pc.nickname, COUNT(pc.nickname) AS numComments
    FROM postComments pc
    GROUP BY pc.nickname
)pc
ON u.nickname = pc.nickname;

这就产生了

Nickname | numPosts | numComments

bob              1             2
sally            2             1
tommy         NULL          NULL
 etc.......

我不想 tommy 待显示。

2vuwiymt

2vuwiymt1#

使用where子句并设置notnull条件

SELECT u.nickname, tpa.numPosts, tpc.numComments
    FROM Users u
    LEFT JOIN
    (SELECT pa.nickname, COUNT(pa.nickname) AS numPosts
        FROM postAuthors pa
        GROUP BY pa.nickname
    )tpa
    ON u.nickname = tpa.nickname LEFT JOIN 
    (SELECT pc.nickname, COUNT(pc.nickname) AS numComments
        FROM postComments pc
        GROUP BY pc.nickname
    )tpc
    ON u.nickname = tpc.nickname;
   where tpa.nickname is not null or tpc.nickname is not null
olqngx59

olqngx592#

您可以通过此条件在页面中显示时控制它。

if(object->property_name==Null && object->property_name==Null ){
 continue;
}
c86crjj0

c86crjj03#

只需添加 WHERE pc.nickname IS NOT NULL OR pa.nickname IS NOT NULL 到查询,即。

SELECT u.nickname, pa.numPosts, pc.numComments
FROM Users u
LEFT JOIN
(SELECT pa.nickname, COUNT(pa.nickname) AS numPosts
    FROM postAuthors pa
    GROUP BY pa.nickname
)pa
ON u.nickname = pa.nickname LEFT JOIN 
(SELECT pc.nickname, COUNT(pc.nickname) AS numComments
    FROM postComments pc
    GROUP BY pc.nickname
)pc
ON u.nickname = pc.nickname
WHERE pc.nickname IS NOT NULL OR pa.nickname IS NOT NULL

这将排除在postauthors和postcomments中都没有值的任何用户。

相关问题