MySQL——查詢操做

簡單查詢

select 選擇查詢列表數據庫

select [listname] from [tablename];
select [listname1] [listname2] from [tablename];

【 * 】 表示顯示全部的列,和建立表時的順序一致性能

避免重複數據

/* 去除列中重複的數據 */
select distinct [listname] from [tablename];
/* 去除每一個數據的列名一、列名2相同 */
select distinct [listname1] [listname2] from [tablename];

圖片描述
圖片描述

實現數學運算查詢

整數、小數類型數據可使用(+ - * /)建立表達式
日期類型數據可以使用(+ -)建立表達式spa

/* 查詢全部貨品id,名稱和批發價(賣價*折扣)*/
select id,productname,saleprice*cutoff from tablename;

/* 查詢全部貨品id,名稱和買50個的成本價 */
select id,productname,costprice*50 from tablename;

設置列的別名

用於表示計算結果的含義
若是別名中使用特殊字符、強制大小寫敏感、空格,都須要單引號設計

/* 給costprice*50取別名爲XXX,其實as能夠省略 */
select id,productname,costprice*50 as XXX from tablename;

設置顯示格式查詢

/* 格式:XXX商品零售價爲:XXX */
select concat(productname,'商品零售價爲:',saleprice) from tablename;

過濾查詢

在from子句後面接where子句code

/* 表格中年齡爲23的數據 */
select * from t_students where age = 23 ;

/* 表格中名字爲楊敏豪的數據,字符串和日期要用單引號括起來 */
select * from t_students where name = '楊敏豪' ;

/* 列名的別名不能用於where子句 */
select name as mingzi from t_students where name != 'Mh' ;
  • 字符串和日期要用[ ' ]單引號括起來
  • 要MySQL查詢時區分大小寫:
/* 默認不區分大小寫 */
select * from t_students where name = 'Mh' ;

/* 在where後面加binary區分大小寫 */
select * from t_students where binary name = 'Mh' ;

圖片描述

SQL的各個子句執行前後順序:排序

  1. from:肯定使用哪一張表作查詢
  2. where:從表中篩選出符合條件的數據
  3. select:將篩選的結果集中顯示
  4. order by:排序
/* AND */
select * from product where saleprice>=300 AND saleprice<=400;
/* OR */
select * from product where saleprice=300 OR saleprice=400;
/* NOT */
select * from product where NOT saleprice=300 ;

若有多個查詢條件,儘可能把過濾最多的條件放在最靠近where的地方,提升性能。圖片

優先級 運算符
1 + - * /
2 NOT
3 AND
4 OR

範圍查詢

between-and,經常使用在數字類型/日期類型數據上,對於字符類型也可用。內存

/* 用between-and語句選擇範圍 */
select * from product where saleprice between 300 and 400;

select * from product where NOT saleprice  between 300 and 400;/*取反*/

集合查詢

in,列的值是否存在於集合中,用於批量刪除字符串

select * from product where id in (2,4);

空值查詢

is null,判斷列的值是否爲空(NULL,不是指的空字符串)數學

select * from product where id is null;

圖片描述

模糊查詢

like,查詢條件可包含文字或數字
【 % 】:能夠表示零或任意多個字符
【 _ 】:可表示一個字符

/* 值以羅技M結尾的 */
select * from product where name like '%羅技M';

/* 值以羅技M開頭的 */
select * from product where name like '羅技M%';

分頁查詢

  • 假分頁/邏輯分頁/內存分頁:

一次性查詢出全部的數據,存放在內存,每次翻頁,都從內存中取出指定的條數。

特色:翻頁較快,可是數據量過大時,可能形成內存溢出。
  • 真分頁/物理分頁/數據庫分頁(推薦):

每次翻頁都從數據庫截取指定的條數,假設每頁10條數據,第一頁:查詢0~9條數據,第二頁:查詢10~19條數據。

特色:翻頁比較慢,不會形成內存溢出

MySQL的分頁設計:

int pagesize = n; /* 表示每頁最多顯示n條數據 */

分頁查詢結果集的SQL:

select * from tablename limit ?,?;

第一個[ ? ]:(當前頁-1)*每頁顯示n條數據
第二個[ ? ]:每頁顯示n條數據

第一頁:SELECT * FROM `test1`.`t_students` LIMIT 0,2
第二頁:SELECT * FROM `test1`.`t_students` LIMIT 2,2
第三頁:SELECT * FROM `test1`.`t_students` LIMIT 4,2
相關文章
相關標籤/搜索