转至牛客网的sql查询训练题,属于最基础的sql查询,适合刚入门的新手。
创建表,插入表的数据
##创建user_profile表
CREATE TABLE `user_profile`
`device_id` int NOT NULL,
`gender` varchar(14) NOT NULL,
`age` int ,
`university` varchar(32) NOT NULL,
`province` varchar(32) NOT NULL);
##插入user_profile表中的数据
INSERT INTO user_profile VALUES(2138,'male',21,'北京大学','BeiJing');
INSERT INTO user_profile VALUES(3214,'male',null,'复旦大学','Shanghai');
INSERT INTO user_profile VALUES(6543,'female',20,'北京大学','BeiJing');
INSERT INTO user_profile VALUES(2315,'female',23,'浙江大学','ZheJiang');
INSERT INTO user_profile VALUES(5432,'male',25,'山东大学','Shandong');
问题1:查询用户user_profile表中所有的数据。
选择全部元组用*
select *
from user_profile;
问题2:想要查询用户的设备id对应的性别、年龄和学校的数据
select device_id,gender,age,university
from user_profile;
问题3:查询用户来自于哪些学校,请从用户信息表中取出学校的去重数据
查询字段前加dictinct可以去除重复数据
select distinct university
from user_profile;
问题4:查看前2个用户的设备ID
查询指定元组用limit m,n 代表从m+1行开始,取n条数据
select device_id
from user_profile limit 0,2;
问题5:查看前2个用户的设备ID,并将列名改为 'user_infos_example'
要更改查询的列名,在列名后 as 新列名,或者空格 新列名都可以
select device_id as user_infos_example from user_profile limit 0,2;
select device_id user_infos_example from user_profile limit 0,2;
问题6:筛选出所有北京大学的学生设备ID
筛选指定条件的元组用where子句
select device_id,university
from user_profile
where university='北京大学';
问题7:查询24岁以上的用户的设备ID、性别、年龄、学校
select device_id,gender,age,university
from user_profile
where age>24;
问题8:查询20岁及以上且23岁及以下的用户的设备ID、性别、年龄
查询一个区间的数据可以使用>,<,=运算符,也可以使用between,但between取的是闭区间。
select device_id,gender,age
from user_profile
where age between 20 and 23;
select device_id,gender,age
from user_profile
where age>=20 and age<=23;
问题10:查看除复旦大学以外的所有用户明细
筛选不满足条件的使用<>,!=,not in 即可,此题也可以使用子查询。
select device_id,gender,age,university
from user_profile
where university != '复旦大学';
select device_id,gender,age,university
from user_profile
where university
not in (
select university from user_profile where university='复旦大学'
);
问题11:查询所有年龄值不为空的用户的设备ID,性别,年龄,学校的信息。
select device_id,gender,age,university
from user_profile
where age is not null;