1. 程式人生 > 實用技巧 >重磅!青島這處新晉網紅打卡地火了,地點就在...

重磅!青島這處新晉網紅打卡地火了,地點就在...

Msql資料管理3

between … and

BETWEEN 操作符在 WHERE 子句中使用,作用是選取介於兩個值之間的資料範圍。這些值可以是數值、文字或者日期。(文字僅支援英文)

語法

WHERE欄位名
BETWEEN值1AND值2

示例: WHERE age BETWEEN 10 AND 20
age欄位的值 在10 到 20 之間會被查出來,並且包含10和20

查詢數值和日期 的範圍 包含 值1 和 值2,及中間的值

實戰

查詢 生日在 1990-01-01 到 2000-01-02 之間的學生資訊

select*
fromstudent
wherebirthdaybetween'1990-01-01'and'2000-01-02';

查詢 sc表 成績 在 80 到 90 分之間 的資料資訊

select*
fromsc
wherescorebetween80and90;

查詢學生表 sid 在 5 和 10 之間的學生資訊

select*
fromstudent
wheresidbetween5and10;

in

in 操作符允許我們在 WHERE 子句中規定多個值。

語法1:

where欄位名in(值1,值2,值3....)

示例: where age in (20,21,25);
age 欄位的值 只要是 20或者21或者25 的資料 都滿足條件

語法2:

wherenotin(值1,值2,值3....)

示例: where age in (20,21,25);

age 欄位的值 只要不是20或者21或者25 的資料 都滿足條件

實戰:

查詢sc表中成績在 70,80,90的資料

select*
fromsc
wherescorein(70,80,90);

查詢sc表中成績不在 70,80,90的資料

select*
fromsc
wherescorenotin(70,80,90);

查詢 學生表中 生日 在 1990-01-01,1990-12-21,2017-12-20,2012-06-06這四天的學生資訊

select*
fromstudent
wherebirthdayin('1990-01-01','1990-12-21','2017-12-20','2012-06-06');

查詢 學生表中 生日 不在 1990-01-01,1990-12-21,2017-12-20,2012-06-06這四天的學生資訊

select*
fromstudent
wherebirthdaynotin('1990-01-01','1990-12-21','2017-12-20','2012-06-06');

limit

MySQL中的分頁查詢, limit 通常放在sql 語句的最末尾

語法1:

limit4

查詢前4條資料

語法2:

limit4,3

從第4條資料之後開始,查詢3條資料
也就是 第5,6,7條的資料

語法3:

limit4offset10;

offset後面的數字是指記錄數
從第10條 之後的資料開始 查詢4條資料
也就是 第 11,12,13,14條資料

實戰

查詢 學生表 中的前五條資料

select*fromstudentlimit5;

查詢 學生表 中10到15條資料,包含第十條和第十五條

select*fromstudentlimit9,6;

查詢 學生表 中10到15條資料,包含第十條和第十五條 ,使用offset關鍵字

select*fromstudentlimit6offset9;

is null

如果欄位沒有要求非空,則欄位值 可以為空,就是null值。如果要查詢某個 欄位 為 null的資料,不能使用 欄位名=null,要用 欄位名 is null;

語法1:

where欄位名isnull;

欄位名 為空的符合條件

語法2:

where欄位名isnotnull;

欄位名 不為空的符合條件

實戰

student表新增兩條資料,要求birthday欄位為空

insertintostudent(sname)values('小明');
insertintostudent(sname,sex)values('小紅','女');
insertintostudent(sname)values('小強');

查詢 student表 生日欄位 為空 的學生

select*
fromstudent
wherebirthdayisnull;

查詢 student表 生日欄位 不為空 的學生

select*
fromstudent
wherebirthdayisnotnull;

查詢 student表 生日欄位 不為空 的 女生

select*
fromstudent
wherebirthdayisnotnull
andsex='女';

查詢 student表 生日欄位 不為空 的 男生

select*
fromstudent
wherebirthdayisnotnull
andsex='男';

別名

起別名是為了後續學習多表聯查 做鋪墊,語法十分簡單

給欄位起別名

比如查詢 student 表的 學生姓名 和 生日 的sql語句:

selectsname,birthdayfromstudent;

image.png

給 sname,birthday欄位 起別名 ,改為中文

selectsnameas姓名,birthdayas生日fromstudent;

image.png

起了別名後,查出來的欄位會以別名展示。
as 關鍵字也可以省略,欄位名 和 別名之間 用空格隔開即可

selectsname姓名,birthday生日fromstudent;

給表起別名

例子:

selecta.sname,a.birthdayfromstudentasa;

給表 起別名 同樣是 使用 as關鍵字(可以使用空格隔開代替as關鍵字), a 就代表 student表,查詢欄位時,可以 使用 a.sname 代表 student的sname欄位。

給表起別名 通常用在 多表查詢,本次使用演示,先熟悉語法。