單表查詢:
SELECT
[ DISTINCT ]
[SQL_CACHE | SQL_NO_CACHE]
select_expr [,select_expr ...]
[FROM table_references [ WHERE where_condition ]
[GROUP BY {col_name | expr |}] [HAVING where_condition]
[ORDER BY [ASC | DESC]]
DISTINCT:數(shù)據(jù)去重
SQL_CACHE:指定存入緩存
SQL_NO_CACHE:指定進(jìn)行緩存
WHERE子句:指定條件,實(shí)現(xiàn)過濾功能
過濾條件:
算數(shù)運(yùn)算:+ - * / % > < >= <=
邏輯運(yùn)算:AND:與運(yùn)算 OR:或運(yùn)算 NOT:非運(yùn)算
字符比較:= !=
列表元素比較:IN (元素1,元素2,元素3,...)
IS NULL:空
IS NOT NULL:非空
LIKE:模糊匹配,能不用盡量不用
RLIKE:基于正則的模糊匹配,能不用盡量不用
GROUP BY子句:更具指定的條件把匹配的結(jié)果進(jìn)行分組,實(shí)現(xiàn)"聚合"運(yùn)算
常用函數(shù):
sum(條件) #求和
max(條件) #最大值
min(條件) #最小值
avg(條件) #平均值
count(條件) #統(tǒng)計(jì)記錄數(shù)
HAVING:對(duì)GROUP BY之后的結(jié)果進(jìn)行過濾
示例:
MySQL> CREATE DATABASE mydb; #創(chuàng)建測試數(shù)據(jù)庫
mysql> USE mydb;
mysql> CREATE TABLE test (id int(50),name varchar(50),qq int(15),gender char(2));#創(chuàng)建測試表
mysql> INSERT INTO test VALUES(1,'zhangshan',12345,'F'); #插入測試數(shù)據(jù)
mysql> INSERT INTO test VALUES(2,'lisi',123142,'F');
mysql> INSERT INTO test VALUES(3,'zsf',124312,'M');
mysql> INSERT INTO test VALUES(4,'yyy',124312,'F');
mysql> INSERT INTO test VALUES(5,'ytt',124312,'M');
單表查詢示例:
mysql> SELECT * FROM test WHERE id>2 AND id<5; #查詢ip大于2小于5的數(shù)據(jù)
mysql> SELECT * FROM test WHERE id>2 GROUP BY gender; #對(duì)性別進(jìn)行分組
mysql> SELECT sum(id),gender FROM test GROUP BY gender; #對(duì)性別進(jìn)行分組,并求他們的id之和
mysql> SELECT * FROM test GROUP BY gender HAVING id>2; #對(duì)性別進(jìn)行分組,顯示id大于2的組
多表關(guān)聯(lián)查詢:
mysql> CREATE TABLE test2 (emain varchar(200),age int(10)); #創(chuàng)建測試環(huán)境
mysql> INSERT INTO test2 values('123@qq.com',10);
mysql> INSERT INTO test2 values('456@qq.com',15);
mysql> INSERT INTO test2 values('789@qq.com',20);
mysql> SELECT test.id,test2.age FROM test,test2 WHERE test.id>2 AND test2.age>10;
test.id #第一章表的id字段
test2.age #第二章表的age字段
test #第一章表 表名
test2 #第二章表 表名
test.id>2 AND test2.age
#拼接顯示test的id字段和test2的age字段,但是test的id字段必須大于2并且test2的age字段必須大于10
mysql> SELECT * FROM test,test2 WHERE test.id>2 AND test2.age>10;
#拼接顯示test,test2的所有字段,但是test的id字段必須大于2并且test2的age字段必須大于10
名稱欄目:mysql基礎(chǔ)(七)select語句
當(dāng)前路徑:
http://weahome.cn/article/geiccg.html