MYSQL基础

来源:互联网 发布:用c语言写九九乘法口诀 编辑:程序博客网 时间:2024/05/22 06:16
MySQL增删改查语句
select * from xxx;
insert into xxx values();
update xxx set xx=xx where xxx=xxx and xxx=xxx;
delete from xxx where xx=xxx and xxx=xxx or……;


MySQL基本语句(增删改查,like语句)


查询:
select 字段名 from 表名;
例1:select * from tablename;//查询全部
例2:select (id,name) from tablename;//查询id,name
例3:select id as studentID from tablename;//查询id,查询出来的表的本来的字段名id变为studentID,as可省略
PS:查询时注意*好不能乱用,否则会导致数据库运行负担。最好是需要什么字段就查询什么字段




增添:
insert into tablename value(xx,xx);
例1:insert into tablename(id,name) value (xx,xx);//增加一行数据,只写了id与name
例2:insert into tablename value();//增加一行数据,括号里写全部信息,用逗号隔开




修改:
update tablename set xx=xx where xx=xx;
例1:updete tablename set id=1 where name="董磊";把name为董磊的id更改为1
例2:updete tablename set id=1 where name="董磊" or iq<10;
把name为董磊或者IQ<10的id更改为1。条件用and、or连接




删除:
delete from tablename where xx=xxx;
例1:delete from tablename;//删除表
例2:delete from tablename where id=1;//把id为1的数据删掉


like语句:
// %代表0到多个字符 
// _代表一个字符
例: selcet name from student where name like '张%'//查询student表中name以张开头的人的name

selcet name from student where name like '张_'//查询student表中name以张开头的2个字的name


distinct


distinct只能返回它的目标字段,无法返回其他字段。所以我们往往用来返回不重复字段的条数
如:(count(distinct id))
用法2: select distinct name from user;查询所有的姓名(重复的只显示一次)
用法3: select distinct name,id from user;查询出所有的姓名与id(只有同时重复的才只显示一次)
用法4:select name,distinct id from user;报,distinct只能放在要查询字段的开头


group by


select name from user group by name;
select sex,COUNT(*) from user GROUP BY sex having +条件;//group by后面写条件用having


//判断一个值是否为null用 is null  is not null


关系运算符 大于> 小于< 不等于!=、<>


order by
select * from emp ORDER BY deptno,sal//先根据deptno排再根据sal排,默认升序(ASC)降序用DESC


select * from emp ORDER BY deptno DESC,sal DESC//都降序排,第一个DESC不能省略,否则第一个为升序


常用基本函数:
1.lower():把字段转换为小写
2.upper():吧字段转换为大写
3.concat(str1,str2,……):将多个字符串连接成一个字符串
3.5.concat_ws(separator,str1,str2,……):将多个字符串连接成一个字符串,中间用separator隔开
4.substr(String str,num start,num length):等同于substring(),mid()从start位置开始取length长度的字符串
PS:第一个字符的位置是1不是0
5.length(str):得到字符串的长度
6.round(num,num):四舍五入函数,第一个参数为小数,第二个为以几位小数来四舍五入
如:ROUND(2.545,2)结果为2.55,ROUND(2.545,1)为2.5


分组函数:
avg(字段):计算出查询结果中该字段的平均值
max(字段):计算出查询结果中该字段的最大值
min(字段):计算出查询结果中该字段的最小值
sum(字段):计算出查询结果中该字段的值的和
count(字段):计算出查询结果中该字段的个数
例:select name,score form studentscore where score>(select avg(score) from studentscore) order by score DESC
子查询:也叫内部查询,如上面的select avg(score) from studentscore就是子查询
查询学生成绩表里分数低于平均成绩的学生姓名和成绩,并根据分数降序排列

原创粉丝点击