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' ;
/* 默認不區分大小寫 */ select * from t_students where name = 'Mh' ; /* 在where後面加binary區分大小寫 */ select * from t_students where binary name = 'Mh' ;
SQL的各個子句執行前後順序:排序
/* 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條數據。
特色:翻頁比較慢,不會形成內存溢出
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