查询之后:
SELECT forum_categories.id AS category_id, forum_categories.title, forum_topics.id AS topic_id, forum_topics.title, user
FROM forum_categories JOIN forum_topics ON forum_categories.id=forum_topics.category_id
LEFT OUTER JOIN forum_views ON forum_topics.id=forum_views.topic_id
WHERE forum_categories.id=6
ORDER BY forum_categories.id
我得到了这个结果:
现在,我想:
- 在选择中添加另一个字段,称为 thereIsANull
- 按
usercategory_id 字段对我的所有结果进行分组
- 如果字段用户(分组时)中没有 NULL,则将 thereIsANull 设置为 1,否则设置为 0。
因此在下面的示例中,结果必须是 1 行:
6 Welcome (some topic_id) (some title) (djfonplaz or null) 0
并且,如果所有用户都不为 NULL:
6 Welcome (some topic_id) (some title) (djfonplaz) 1
如何在 MySql 上实现?
最佳答案
SELECT
forum_categories.id AS category_ids
, forum_categories.title as titles
, forum_topics.id AS topic_ids
, forum_topics.title as topic_titles
, count(*) as NumberOfRows
, GROUP_CONCAT(IFNULL(user,'(no user)')) AS users
, (count(*) - count(user)) as IsThereANull
FROM forum_categories
INNER JOIN forum_topics ON forum_categories.id=forum_topics.category_id
LEFT OUTER JOIN forum_views ON forum_topics.id=forum_views.topic_id
WHERE forum_categories.id=6
GROUP BY category_id
ORDER BY forum_categories.id
如果没有 null,IsThereANull 将为 0
,如果有,则为 1 或更多。
关于mysql - 如何对 NULL 字段进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7653950/