sql基础使用
聚焦一下sql数据库的一些基础类型、基础功能进行学习,主要还是用得少,想加强训练。
如下是一个简单数据表:
drop table if exists user_profile;
CREATE TABLE `user_profile` (
`id` int NOT NULL,
`device_id` int NOT NULL,
`gender` varchar(14) NOT NULL,
`age` int ,
`university` varchar(32) NOT NULL,
`province` varchar(32) NOT NULL);
INSERT INTO user_profile VALUES(1,2138,'male',21,'北京大学','BeiJing');
INSERT INTO user_profile VALUES(2,3214,'male',null,'复旦大学','Shanghai');
INSERT INTO user_profile VALUES(3,6543,'female',20,'北京大学','BeiJing');
INSERT INTO user_profile VALUES(4,2315,'female',23,'浙江大学','ZheJiang');
INSERT INTO user_profile VALUES(5,5432,'male',25,'山东大学','Shandong');
查询所有列:
select * from user_profile
查询设备id、性别、年龄和学校信息:
select device_id, gender, age, university from user_profile;
查询数据去重,比如只需要学校信息,那就不能要重复的:
select distinct university from user_profile;
查询数据中靠前那几个,可以用top:
select device_id from user_profile limit 2;
使用limit来进行限制,除此以外,上面的id也可以进行利用:
select device_id from user_profile where id <=2;
查询某列信息并给该列重命名
select device_id as user_infos_example from user_profile where id<=2;
使用as来给起别名,这算是个临时操作。
查询特定信息
select device_id, university from user_profile where university='北京大学';
可以显式where指定的,也可以不显示,就像上面的where id,就只是个限制条件。不过上面的北京大学这是字符串,不用单引号指定会出问题(不知道英文字符串咋样)。
查询指定范围的信息
使用between加and来指定范围,也可以使用大小判断加and。在指定某个确切不是的值,可以用!=,也可以用not like,还可以用not in()指定,如果是字符串值,单引号不能少:
除了and以外,还有用or来指定条件
进行两种复杂条件的判断查询
drop table if exists user_profile;
CREATE TABLE `user_profile` (
`id` int NOT NULL,
`device_id` int NOT NULL,
`gender` varchar(14) NOT NULL,
`age` int ,
`university` varchar(32) NOT NULL,
`province` varchar(32) NOT NULL,
`gpa` float);
INSERT INTO user_profile VALUES(1,2138,'male',21,'北京大学','BeiJing',3.4);
INSERT INTO user_profile VALUES(2,3214,'male',null,'复旦大学','Shanghai',4.0);
INSERT INTO user_profile VALUES(3,6543,'female',20,'北京大学','BeiJing',3.2);
INSERT INTO user_profile VALUES(4,2315,'female',23,'浙江大学','ZheJiang',3.6);
INSERT INTO user_profile VALUES(5,5432,'male',25,'山东大学','Shandong',3.8);
比如想要得到gpa在3.5以上的山东大学学生信息,或者gpa在3.8以上的复旦大学学生信息:
select device_id, gender, age, university, gpa from user_profile where gpa>3.8 and university='复旦大学'
union
select device_id, gender, age, university, gpa from user_profile where gpa>3.5 and university='山东大学';
也可以用括号把这些个条件给括起来:
select device_id, gender, age, university, gpa from user_profile where (gpa>3.8 and university='复旦大学') or (gpa>3.5 and university='山东大学');
使用通配符
在涉及到字符串信息的时候,往往不会给定一个字符串值,而是给出部分字符串,让它模糊查询,这时候就需要使用通配符了,_符号表示匹配一个任意字符,%表示匹配0个或多个字符,[]表示匹配里面的字符,[^]表示不匹配里面的字符。
使用函数
在mysql中有合适的聚合函数可以利用,比如max,就可以查询特定列中最大的数值:
select max(gpa) from user_profile where university='复旦大学';
如果有范围,还可以使用round来指定范围,用max来指定最大值,然后自己指定最小值。嗯,也可以使用limit。
计算行数和平均值
select count(gender) male_num, round(avg(gpa), 1) avg_gpa from user_profile where gender='male';
上面使用count来进行同类计算,然后起别名为male_num,用round来指定对应值然后取别名avg_gpa,最后使用where来指定只输出male字段。

浙公网安备 33010602011771号