目錄
一、基礎查詢
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個或多個字符;
//[ ]:匹配[ ]中的任意一個字符(若要比較的字符是連續的,則可以用連字符“-”表 達 );
//[^ ]:不匹配[ ]中的任意一個字符。