一、常用的查詢陳述句
1.SELECT:欄位運算式
select既可以做查詢,也可以做輸出
select rand(); -- 輸出亂數
select unix_timestamp(); -- 顯示Unix時間戳
select id, name from student;
2.FROM子句
語法:select 欄位 from 表名
FROM后面是資料源,資料源可以寫多個,資料源一般是表名,也可以是其他查詢的結果
select student.name, score.math from student, score;
3.WHERE子句:按指定條件過濾
語法:select 欄位 from 表名 where 條件;
WHERE是做條件查詢,只回傳結果為True的資料
#將student表中city=陜西的name值查找出來
select name fron student where city='陜西';
空值判斷:is null | is not null
select name from student where description is null;
select name from student where description is not null;
范圍判斷:between …and … | not between … and …
#查詢score表中math值位于60~70之間的id和math
select id, math from score where math between 60 and 70;
#查詢score表中math值不在60~70之間的id和math
select id, math from score where math not between 60 and 70;
#查詢score表中math值大于等于80并且english值小于等于60的資料
select * from score where math>=80 and english<=60;
4.HAVING
HAVING和WHERE功能類似,都可以用來實作條件查詢,很多情況下可以用where或者having,甚至可以混合使用,
select name, birthday from student where birthday > '1995-1-1';
select name, birthday from student having birthday > '1995-1-1';
select * from student where id>=3 and city='西安';
select * from student having id>=3 and city='西安';
select * from student where id>=3 having city='西安';
where和having的區別:
只能用是where的情況
select name, birthday from student where id > 2;
#報錯,having的條件查詢,只能包含在前面的搜索結果里
select name, birthday from student having id >2;
只能使用having的情況
select name as n, birthday as b, id as i from student having i > 2;
#報錯,where的條件查詢只識別存在的欄位
select name as n, birthday as b, id as i from student where i > 2;
having后面可以跟聚合函式,where不行,
select city, min(birthday) from student group by city having min(birthday)>='1996';
5.GROUP BY:分組查詢
按照某一欄位進行分組,會把該欄位中值相同的歸為一組,將查詢結果分類顯示,
如果有where要放在where的后面
語法:select 欄位 from 表名 group by 分組欄位;
select sex, count(id) from student group by sex;
#在group將需要的結果通過聚合函式拼接
select sex, group_concat(name) from student group by sex;
6.ORDER BY:按欄位排序
ORDER BY主要作用是排序
ORDER BY寫在GROUP BY后面,如果有having也要寫在having后面
語法:select 欄位 from 表名 order by 排序欄位 asc|desc;
升序asc 降序desc 默認asc
select * from student order by age;
select * from student order by age desc;
7.LIMIT:限制取出數量
#從第1行到m行
select 欄位 from 表名 limit m;
#從第m行開始,往下取n行
select 欄位 from 表名 limit m, n;
#跳過前n行,取后面的m行
select 欄位 from 表名 limit m offset n;
8.DISTINCT:去重
select distinct city from student;
二、函式
聚合函式
| Name | Description |
|---|---|
| AVG() | 回傳平均值 |
| COUNT() | 計數 |
| GROUP_CONCAT() | 回傳連接的字串 |
| MAX() | 回傳最大值 |
| MIN() | 回傳最小值 |
| SUM() | 回傳總和 |
數值計算類函式
| NAME | Description |
|---|---|
| ABS(x) | 回傳x的絕對值 |
| CEIL(x) | 回傳大于x的最大整數值 |
| FLOOR(x) | 回傳小于x的最大整數值 |
| MOD(x, y) | 回傳x/y的模 |
| RAND() | 回傳0到1內的隨機值 |
| ROUND(x, y) | 回傳引數x的四舍五入的有y位小數的值 |
| TRUNCATE(x, y) | 回傳數字x截斷為y位小數的結果 |
日期時間相關
| NAME | Description |
|---|---|
| NOW() | 回傳現在的日期時間 |
| DATEDIFF(x, y) | 回傳起始時間x和結束時間y之間的天數 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/62982.html
標籤:其他
上一篇:資料庫期末復習
下一篇:MySQL基本操作
