1. 程式人生 > >MySQL(04)——SQL語句之資料表內容的查詢

MySQL(04)——SQL語句之資料表內容的查詢

這個大概是使用最多的命令了。 因為平時插入資料都是程式寫好來插入的,自己不會手動插入資料; 建庫建表也不是自己操心的事; 修改資料的例子也很少; 刪除資料?這個事幾乎不幹。 剩下的也就是查詢資料了。

create table student(
	id int primary key auto_increment,
    name varchar(32) not null,
	age int ,
	gender varchar(10) not null,
	score double not null,
	birthday date
);

insert into student (id,name,age,gender,score,birthday) values(null,'zhangsan',23,'male',98.99,'1999-09-09');
insert into student (id,name,age,gender,score,birthday) values(null,'lisi',23,'男',56.99,'1997-02-09');
insert into student (id,name,age,gender,score,birthday) values(null,'wangwu',24,'女',75.99,'1998-01-01');
insert into student (id,name,age,gender,score,birthday) values(null,'liuliu',25,'男',80.99,'1999-11-12');

找了段資料,建表插入資料,準備查詢,

查詢資料庫中的某張表的所有資料

語法:select * from 表名; select * from student;

查詢某張表中指定的列

語法: select 列名,列名… from 表名;

按條件查詢

select 列名,列名… from 表名 where 條件; select name,score from student where score>60;

運算子

1.相等 = 不等<> != 2.and 邏輯與 or 邏輯或 not 邏輯非 3.區間 between …and… 在兩者之間取值,等價於>=前面 <=後面 age >=24 and age<=50 等價於 age between 24 and 50

4.in (值1,值2,值3…) 在指定值中任意取值 where 列名 in(值,值,值…)等價於where 列名=值 or 列名=值 or列名=值…

5.like 模糊查詢 like ‘模糊查詢pattern’ 進行模糊查詢,表示式有兩個佔位符:% 任意字串 任意單個字元 name like ‘張%’ 所有姓張學員 %張% 含有張的學員 name like '張’ 所有姓張名字為兩個字學員 6.is null 判斷該列值為空 is not null 不為空;

過濾重複資料distinct

查詢排重 select distinct 列名 from 表名[where 條件] 對查詢的結果進行排序

order by 子句進行排序

select * from 表名 order by 列名 asc|desc; asc 是升序排列,desc 是降序排列; select * from student order by age desc,score desc;

別名,對查詢出來的列名起別名

select 列名 as 別名,列名 as 別名…from 表名 where 條件; 在使用別名時,as關鍵字可以省略; select age score from student; select age , score from student;

sql中的聚合函式

count函式 select count(*)|count(列名) from 表名;

sum函式 select sum(列名) from 表名; 1.如果使用sum 多列進行求和的時候,如果某一列中的有null,這一列所在的行中的其他資料不會被加到總和。 2、可以使用mysql 資料庫提供的函式 ifnull(列名,值) 3、在資料庫中定義double型別資料,是一個近似值,需要確定準確的位數,這時可以把這一列設計成numeric型別。numeric(資料的總列數,小數位數) 語法:truncate(列名, 小數的位數) select truncate(sum(ifnull(age,0) + ifnull(score,0)),2) from student; 擷取2位小數;

avg函式 select avg(列名) from 表名;

max,min函式 max/min 函式返回滿足where條件的一列的最大/最小值;

group by 分組函式

語法:select … from … group by 列名,列名 分組: 按照某一列或者某幾列。把相同的資料,進行合併輸出。 select …from …where…group by…having…order by… from 1 [where 2] [group by 3] [having 4] [order by 5] select 6 聚合函式只能出現在4,5,6 1、聚集函式:分組之後進行計算; 2、通常 select的內容:a 被分組的列,b 聚集函式。 4、如果使用group by 對資料進行分組之後還要過濾。這時一般不能使用where,因為where關鍵字的後面不能跟上面講解的這些函式。如果需要在過濾的條件中加上述的函式,只能使用having關鍵字。

5、where 後不能跟 聚合函式,having中可以跟 聚合函式。

標準SQL的解析順序為:

(1)from 子句, 組裝來自不同資料來源的資料 (2)where子句, 基於指定的條件對記錄進行篩選 (3)group by 子句, 將子句劃分為多個分組 (4)使用聚合函式進行計算 (5)使用having子句篩選分組 (6)計算所有的表示式 (7)使用order by 對結果集進行排序