按一个字段分组,但如果为空则按另一个字段分组
我有一个表,其中有一列名为 tableNum ,另一列名为 deviceNum
我想按 tableNum 分组,但如果 tableNum 为空,那么我需要按 deviceNum 分组。
我目前已经使用 union 语句完成了此操作,以便我可以执行两个不同的语句,但想知道是否有更好的方法。
非常感谢
戴夫
I have a table that has a column called tableNum and another column called deviceNum
I would like to group by tableNum, but if tableNum is empty then I would need to group by deviceNum.
I have currently done this with a union statement so that I could do two different statements, but wondered if there were a better way.
Many thanks
Dave
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以按 coalesce/ifnull 进行分组(在本例中它们是相同的):
请参阅文档:
http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#function_coalesce
你可能有一些无意义的如果 tableNum 和 deviceNum 两列包含相同的值,则对这两个列之间的冲突进行分组。根据您想要获得的结果类型,您可以编写类似这样的内容,以避免冲突:
但这可能会很慢,但是,与
CONCAT
一样,没有机会使用索引。只是给你一个想法。注意:正如 ypercube 所说,UNION 会更快,因为 MySQL 可以并行子查询You can group by coalesce/ifnull (they're the same in this example):
See the documentation:
http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#function_coalesce
You might have some meaningless grouping collisions between tableNum and deviceNum, should the two columns hold identical values. Depending on what type of result you want to get, you could then write something like this, to avoid collisions:
This might be quite slow, though, as with
CONCAT
there is no chance of using indexes... Just to give you an idea. Note: as ypercube stated,UNION
's thend to be faster because MySQL can parallelise subqueries保留
UNION
并根据您的要求使用UNION ALL
使其发挥作用。它可能比其他解决方案快得多(或者可以优化运行)。
我不想翻译这个或必须在没有
UNION
的情况下优化它:Keep the
UNION
and make it work, as your requirements, withUNION ALL
.It will probably be (or can be optimized to run) much faster than other solutions.
I wouldn't like to translate this or have to optimize it without
UNION
:试试这个:
Try this:
GROUP BY (IFNULL(child_id,parent_id))
GROUP BY (IFNULL(child_id, parent_id))