【MySQL】牛客网sql语句简单例题,sql入门
目录
一、基础查询
1、查询所有列
2、 查询多列
二、简单处理查询结果
1、查询结果去重
2、查询结果限制返回列数
3、将查询后的列重新命名
三、条件查询之基础排序
1、查找后排序
2、 查找后多列排序
3、查找后降序排列
四、条件查询之基础操作符
1、查找学校是北大的学生信息
2、 查找某个年龄段的用户信息
3、查找除复旦大学的用户信息
4、用where过滤空值练习
五、条件查询之高级操作符
1、Where in 和 Not in
2、操作符混合应用
3、查看学校名称中含北京的用户
所有题目对应网址:牛客网在线编程_编程学习|练习题_数据结构|系统设计题库
一、基础查询
1、查询所有列
解法1:
SELECT *
FROM user_profile;解法2:
select
id,device_id,gender,age,university,province
from user_profile//注意sql语句没那么严格,不用太纠结大小写问题,sql关键字推荐大写,为了观看更美观突出。
2、 查询多列
SELECT device_id,gender,age,university
from user_profile
二、简单处理查询结果
1、查询结果去重
解法1:
select university from user_profile group by university;解法2:
distinct 关键字
select distinct university from user_profile;
2、查询结果限制返回列数
解法1:
select device_id from user_profile limit 2;
//解法2的简写解法2:
select device_id from user_profile limit 0,2;
//limit 0,2表示从第一条数据开始(0代表第一条),每页只显示2条数据解法3:
select device_id from user_profile where id <=2;
//查询id值<=2的数据
3、将查询后的列重新命名
SELECT device_id AS user_infos_example
FROM user_profile
LIMIT 2;
//1.AS 写不写都可以
//2.别名加不加引号(单双)都可//加引号:别名就是引号内的内容。//不加引号:别名如果为小写,会解析为大写,别名实际为大写。
//以上两点在调用别名时要注意,易报错:找不到对应的列(大小写对应的是不同的列)
三、条件查询之基础排序
1、查找后排序
SELECT device_id, age
FROM user_profile
ORDER BY age ASC;
// order by + 列名 + asc/desc:根据那一列升序/降序
2、 查找后多列排序
SELECT device_id, gpa, age
FROM user_profile
ORDER BY gpa ASC, age ASC;
//详解见上一道题
3、查找后降序排列
//order by +属性+后面不写默认为升序
select device_id,gpa,age from user_profile order by gpa desc,age desc;
四、条件查询之基础操作符
1、查找学校是北大的学生信息
SELECT device_id, university
FROM user_profile
WHERE university = '北京大学';
2、 查找某个年龄段的用户信息
解法1:
between表范围
select
device_id,
gender,
age,
university
from user_profile
WHERE
age between 20 and 23解法2:
用and的来连接条件范围
SELECT
device_id,
gender,
age
from user_profile
WHERE
age >= 20 and age<=23
3、查找除复旦大学的用户信息
解法1:
select device_id,gender,age,university from user_profile where university <> '复旦大学'解法2:
select device_id,gender,age,university from user_profile where university != '复旦大学'解法3:
select device_id,gender,age,university from user_profile where university NOT IN ("复旦大学")
4、用where过滤空值练习
select device_id,gender,age,university
from user_profile
where age is not null and age <> ""//空值和空字符串的过滤
五、条件查询之高级操作符
1、Where in 和 Not in
SELECT device_id, gender, age, university, gpa
FROM user_profile
WHERE university IN ('北京大学', '复旦大学', '山东大学');
2、操作符混合应用
//子查询方式
select
device_id,
gender,
age,
university,
gpa
from user_profile
where
device_id in (select device_id from user_profile where gpa>3.5 and university='山东大学')
or
device_id in (select device_id from user_profile where gpa>3.8 and university='复旦大学')
3、查看学校名称中含北京的用户
SELECT device_id,age,university FROM user_profile
WHERE university LIKE '%北京%'//匹配串中可包含如下四种通配符:
//_:匹配任意一个字符;
//%:匹配0个或多个字符;
//[ ]:匹配[ ]中的任意一个字符(若要比较的字符是连续的,则可以用连字符“-”表 达 );
//[^ ]:不匹配[ ]中的任意一个字符。