您的位置:首页 > 数据库 > MySQL

SQL查询、排序(mysql下)

2016-12-23 14:08 399 查看

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
排序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: