结束标识符; 每一句sql语句以;为结尾。
检索多个列 最后一个字段后不要加逗号,,否则会报错
检索不同的行 利用distinct
1 selectdistinctusernamefromuser; 限制结果 利用limit
1 selectdistinctusernamefromuserlimit1,10; 返回从行1开始的10行(0-index)
等价写法:
1 selectdistinctusernamefromuserlimit10offset1; 使用完全限定的表名 1 selectdistinctuser.usernamefromuserlimit10offset1;
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'; 数值处理函数