order by 1 selectusernamefromuserorderbyage; 按多个列排序 1 selectusernamefromuserorderbyage,weight,username; 先按age进行排序,age相同则按weight排序,age、weight都相同,则按username进行排序
指定排序方向 desc(从高到低) asc(从低到高) 1 selectusernamefromuserorderbyusernamedesc;
where子句 order by在where子句后面
字符串 用单引号把字符串包括在内
范围值检查between 1 selectusernamefromuserwhereagebetween18and23; [18, 23]
空值检查 is null is not null
and 和 or where 子句优先处理and,再处理or
1 2 3 selectprod_name,prod_pricefromproductswherevend_id=1002orvend_id=1003andprod_price>=10 可以看成是:
1 2 3 selectprod_name,prod_pricefromproductswhere(vend_id=1002)or(vend_id=1003andprod_price>=10) in操作符 1 selectusernamefromuserwhereuidin(1,2,3); 将要查询的值放在一个括号中
in操作符一般比or操作符快 in最大的优点是可以包含其他select语句 not 操作符
like操作符 百分号%通配符 表示任意字符出现任意次数
1 selecttitlefrompassagewherecontentlike'tom cat%' 匹配以tom cat开头的内容,接受tom cat之后的任意字符,不管它有多少字符
通配符可以在搜索模式中任意位置使用
1 selecttitlefrompassagewherecontentlike'%jerry%'; null无法用通配符匹配
下划线_通配符 _通配符只能匹配一个字符
使用通配符的技巧 不要过度使用通配符 尽量不要在开头处使用通配符 注意通配符的位置
使用正则表达式 1 selectuidfromuserwhereusernameregexp''; 搜索两个串之一 1 selectuidfromuserwhereusernameregexp'|' 匹配字符类 略
concat拼接字段 1 selectconcat(firstname,'.',lastname)asnamefromuser; 使用别名 1 selectusernameasnamefromuser;
处理文本串的函数 soundex() 数据库中没有目标,但是可以找到与目标类似的
日期函数 1 selectorder_idfromorderswhereorder_date='2021-07-19'; 分析上面的查询,order_date若是datetime类型,则需要改为:
1 selectorder_idfromorderswhereDate(order_date)='2021-07-19'; 获取一个月内的记录:
1 2 3 4 selectorder_idfromorderswhereDate(order_date)between'2021-07-01'and'2021-07-31'; 数值处理函数
我们经常需要汇总数据而不用把它们实际检索出来,这些情形有:
确定表中行数(满足某个条件或包含某个特定值的行数) 获取表中行组的和 找出表列(或所有行或某些特定行)的最大值、最小值和平均值 5个聚集函数 注意聚集函数运行在行组上,即通常依赖于group by,或者是指定值的where语句
avg忽略列值为NULL的行 count(*)对行进行计数,包括NULL值, count(列名)不统计NULL max, min忽略列值为NULL的行 distinct 不指明distinct,默认是all distinct必须指明列名 组合聚集名字 用了聚集函数最好起别名,便于debug