Select with condition

旧时模样 提交于 2019-12-13 03:44:07

问题


I need some help about select with condition, right now I'm doing this:

                GROUP_CONCAT(
                    CASE WHEN glpi_tickets.users_id_lastupdater = glpi_users.id THEN
                        CONCAT(glpi_users.firstname, ' ', glpi_users.realname) 
                    END SEPARATOR '<br>') AS last_updater

I select firstname and realname when users_id_lastupdater = id

I guess there is a better way to do this?


回答1:


group_concat seems like overkill for this. You could just use max():

max(CASE WHEN glpi_tickets.users_id_lastupdater = glpi_users.id
         THEN CONCAT(glpi_users.firstname, ' ', glpi_users.realname) 
    END) AS last_updater

The separator isn't needed because it isn't used for only one element.

EDIT:

The max() function takes the maximum of value of an argument. In this case, it is conditional because of the case. When the condition is not met, the values are NULL (no else clause). So, it retrieves the value when the condition is met. If multiple row match the condition, it retrieves the largest value.



来源:https://stackoverflow.com/questions/17777098/select-with-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!