SQL查询、排序(mysql下)

    xiaoxiao2021-03-25  17

    1. 查询

    (1)连接列值

    select concat(column1, 'your string', column2) as new_column from table

    使用concat函数连接来自多个列的数值。

    (2)使用条件逻辑

    select column1, column2, case when column2 <= 100 then 'bad' case when column2 >= 500 then 'perfact' else 'good' end as status from table

    这将会创建一个新列status,它的值由条件决定。如果没有使用else,对于不满足条件的,case表达式会返回null。

    (3)随机返回记录

    select * from table order by rand() limit 5

    同时使用rand函数、limit和order by可以达到此效果。

    注意:在order by子句中指定数字常量时,是要求根据select列表中相应位置的列来排序;在order by子句中使用函数时,则按函数在每一行计算结果排序。

    (4)查找null

    匹配null时,必须使用is null,不能使用= null

    (5)转换null

    你可以使用非null值来代替null值

    select coalesce(column, 0) from table

    这里,将column为null的值替换为0。

    2. 排序

    (1)基本排序

    指定列名 select column1,column2 from table order by column1 [asc|desc], column2 [asc|desc] 指定列编号 select column1,column2 from table order by 1 [asc|desc], 2 [asc|desc]

    (2)按子串排序

    select column1, column2 from table order by substring(column1, len(column1, 2))

    表明按照column1的最后两个字符排序。

    (3)处理排序的null值

    思路是先产生一张带有is_null信息的临时表,然后先按is_null排序,再按你需要的列排序:

    select column1, column2 from ( select column1, column2 case when column1 is null then 1 else 0 end as is_null from table) t1 order by is_null, column1

    表明按照column1升序排序,null放最后。

    (4)排序里面添加条件逻辑

    使用case表达式:

    select column1, column2, column3 from table order by case when column1 = ' ' then column2 else column3 end

    表明当column1的值为' '时,按照column2排序;否则按照column3排序。

    转载请注明原文地址: https://ju.6miu.com/read-300153.html

    最新回复(0)