单表查询:
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:数据去重
SQL_CACHE:指定存入缓存
SQL_NO_CACHE:指定进行缓存
WHERE子句:指定条件,实现过滤功能
过滤条件:
算数运算:
+
-
*
/
%
> < >
=
<
=
逻辑运算:AND:与运算 OR:或运算 NOT:非运算
字符比较:
=
!
=
列表元素比较:IN (元素
1
,元素
2
,元素
3
,...)
IS NULL:空
IS NOT NULL:非空
LIKE:模糊匹配,能不用尽量不用
RLIKE:基于正则的模糊匹配,能不用尽量不用
GROUP BY子句:更具指定的条件把匹配的结果进行分组,实现
"聚合"
运算
常用函数:
sum
(条件)
max
(条件)
min
(条件)
avg(条件)
count(条件)
HAVING:对GROUP BY之后的结果进行过滤
示例:
mysql> CREATE DATABASE mydb;
mysql> USE mydb;
mysql> CREATE TABLE test (
id
int
(
50
),name varchar(
50
),qq
int
(
15
),gender char(
2
));
mysql> INSERT INTO test VALUES(
1
,
'zhangshan'
,
12345
,
'F'
);
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
;
mysql> SELECT
*
FROM test WHERE
id
>
2
GROUP BY gender;
mysql> SELECT
sum
(
id
),gender FROM test GROUP BY gender;
mysql> SELECT
*
FROM test GROUP BY gender HAVING
id
>
2
;
多表关联查询:
mysql> CREATE TABLE test2 (emain varchar(
200
),age
int
(
10
));
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
test2.age
test
test2
test.
id
>
2
AND test2.age
mysql> SELECT
*
FROM test,test2 WHERE test.
id
>
2
AND test2.age>
10
;