如何对 NULL 字段进行分组
在这个查询之后:
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 - 设置 thereIsANull 对我的所有结果进行分组到如果 user 字段中不存在 NULL(分组时),则为 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 上执行此操作?
After this query :
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
I got this results :
Now, I'd like to :
- add another field in the select, called thereIsANull
- group all my results by the field
usercategory_id - setting thereIsANull to 1 if there isn't a NULL in the field user (while grouping), 0 otherwise.
So in the example below, the result must be 1 row :
6 Welcome (some topic_id) (some title) (djfonplaz or null) 0
and, if all user was different from NULL :
6 Welcome (some topic_id) (some title) (djfonplaz) 1
How can I do it on MySql?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果不存在 null,则 IsThereANull 将为
0
;如果存在,则为 1 或更多。IsThereANull will be
0
is there's no null and 1 or more if there is.我认为以下查询应该得到您正在寻找的结果:
I think that the following query should get the result that you are looking for:
我认为这样的事情会如您所愿:
假设在forum_categories表中找到了字段用户,否则只需修改子查询以加入您从中获取用户的表
请注意,Thiis基本上与< a href="https://stackoverflow.com/users/263671/cez">Cez 写道,所以他值得一些功劳,唯一的区别是子查询和按类别 id 而不是用户分组。
尝试一下,让我知道它是否正确:)
I think something like this would do as you want:
Assuming that the field user is found in the forum_categories table, other wise just modify the subquery to join that table where you get the user from
Note that Thiis is basically the same as the one Cez wrote, so he deserves some credits to, only difference is the subquery and grouping by category id instead of user.
Try it out and let me know if it was correct :)