Mysql--sql语句

来源:互联网 发布:360 云盘mac如何使用 编辑:程序博客网 时间:2024/06/10 01:16

1.查找想要的记录

select * from 表名 where 条件

select * from 表名 as 新名字  where 条件

select字段1,字段2 from 表名 where 条件

select 表.字段1,表.字段2  from 表名 where 条件


2.查询结果进行分组

group by


3.查询结果按条件进行分组

having


4.查询结果进行一定的条件排序显示

order by   asc(升序)desc(降序)


5.显示结果按限制进行显示

limit M----------从第一条开始返回,返回M条记录(记录从0开始计算)

limit m,n---从第M+1条记录开始,显示以下的N条


6.子查询 sql语句中还有select

select * from tb1 where col1=(select col2 from tb2)

外层查询:select、insert、update、set、do

子查询:select、distinct、group by、order by、limit、函数


7.比较运算符引发的子查询

=     >=     <=


8.not in/exists引发子查询--in代表or

select * from tb1 where page=100 or page=1000

等于

select * from tb1 where page in(100,1000)


8.多表连接

表1 inner join 表2 on 表1.字段1=表2.字段2

内连接:inner join--只有两个表相匹配的行才能在结果集中出现

左内连接:包含左表所有行以及右表匹配行

右内连接:包含右表所有行以及左表匹配行

外连接:outer join----取消所有限制,直接连接两个表

左外连接--左表不做限制

右外连接--右表不做限制


函数

字符函数:

concat()---连接字符     eg: select concat(‘mysql’,'abc')        select concat(字段1,字段2)  as 字段输出   from 表1

concat WS()---使用指定的间隔符连接字符   eg: select concat('|',‘mysql’,'abc')  

format ()---格式化   eg:format("%d","%d",[1,2])     select format(1234.23,2)

lower()--小写字母

upper()--大写字母

left()--获取左侧字符  select  left(“mysql”,2) 输出my

right()--获取右侧字符

length()---获取长度

ltrim()----删除左边空格

rtrim()--删除右边空格

trim()--删除空格

substring()--截取字符串的一段

replace()--替换字符串

数值运算

ceil()----向上取整    select  ceil(5.01)输出6

floor()---向下取整  select  floor(5.99)输出5

div()--整除  select  floor(3/4)  输出0

mod()--取余数  select  5 mod 3 输出2    select 5.3 mod 3 输出2.3

power()---幂运算  select power(2,3) 输出8

round()--四舍五入,和常识一样  select round(2.135,2) 输出2.14

truncate()---截断  select truncate(2.134,2) 输出2.13


比较运算

(not)between。。and

(not)in

is (not)null  


日期函数

now()--当前日期和函数

curdate()---当前日期

curtime()--当前时间

date—add()---日期变化  select  date—add(“2014-12-25”,1year)输出2015-12-25

dateiff()--日期差  select  dateiff(“2014-12-25”,“2015-12-25”,)输出-365

date—format()--日期格式化


聚合函数--只返回一个值

avg()--平均

sum()--求和

count()--计数

max()--最大

min()--最小


信息函数

connection_id()-----连接的线程ID

datebase()---当前数据库

last_insert_id()-----最后插入的id号      前提是存在自动编号的字段 如自动编号从1到4,新增了第5条记录,select last_insert_id()可获得5,如同时新增多条记录,只显示第一条新增记录的ID

user()---当前用户

version()---当前数据库版本


加密函数

MD5()---MD加密

password()--加密码


自定义函数

create function 函数名()  returns 返回值类型(长度)-------创建自定义函数

return  内容------返回

routine_body----函数体,可以是简单的selcect ,循环等,也可以是复杂语句,使用begin end

调用--select 

 eg:无参数的自定义函数:图1等同于图2



有参数的自定义函数



0 0
原创粉丝点击