SELECT
[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
[SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr [, select_expr ...]
[FROM table_references
[WHERE where_condition]
[GROUP BY {col_name | expr | position}
[ASC | DESC], ... [WITH ROLLUP]]
[HAVING where_condition]
[ORDER BY {col_name | expr | position}
[ASC | DESC], ...]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[PROCEDURE procedure_name(argument_list)]
[INTO OUTFILE 'file_name'
[CHARACTER SET charset_name]
export_options
| INTO DUMPFILE 'file_name'
| INTO var_name [, var_name]]
[FOR UPDATE | LOCK IN SHARE MODE]]
簡化一下語法如下:
select column1,column2,...
from table1,table2,...
[where condition]
[group by …]
[having …]
[order by …]
1、例如:下面例子
MySQL> create table jokes(
-> id int unsigned not null auto_increment primary key,
-> joketext text,
-> jokedate date
-> )engine=myisam charset=utf8;
MySQL> insert into jokes values('','why not?',now());
#計算列(select 用於檢索從一個或多個表中選取出的行。Select也可以被用於檢索沒有引用任何表的計算列)
select 1+1 as total; //結果為2
+-------+
| total |
+-------+
| 2 |
+-------+
#從表Jokes中挑選所有的東西
select * from jokes;
+----+----------+------------+
| id | joketext | jokedate |
+----+----------+------------+
| 1 | why not? | 2010-04-08 |
+----+----------+------------+
#選擇感興趣的列(投影)
select id, jokedate from jokes;
#我們是不是可以多少顯示一點笑話正文的內容呢?(預覽)
MySQL> select id,left(joketext,3) as content,jokedate from jokes;
+----+---------+------------+
| id | content | jokedate |
+----+---------+------------+
| 1 | why | 2010-04-08 |
+----+---------+------------+
#統計表中記錄數
MySQL> select count(*) as records from jokes;
+---------+
| records |
+---------+
| 1 |
+---------+
#統計2000年1月1日之後錄入的笑話記錄數
select count(*) from jokes where jokedate >= ‘2000-01-01’;
#笑話裡包含”鞋” //%表示任一字符
MySQL> select joketext as content from jokes where joketext like '%not%';
+----------+
| content |
+----------+
| why not? |
+----------+
#顯示2000年4月份的包含“鞋”的笑話(組合查詢)
select joketext from where joketext like “%not%” and jokedate >= “2000-04-01” and jokedate < “2000-05-1”;
2、分組語句
員工表emp(empno, name, tel, deptno, sal)
部門表dept(deptno, dname, addr)
1)顯示每個部門的最高工資
select deptno, max(sal) from emp group by deptno;
select deptno,max(sal) as ‘最高工資’ from emp group by deptno;
注意:max()、min()…函數在顯示列中出現時,必須與group by一起使用
3、嵌套子查詢
1)顯示每個部門收入最高的職工信息。
select * from emp
where sal in ( select max(sal) from emp
group by deptno );(先按組排序,後顯示一組中最大的)
2)按照工資高低顯示職工信息
select * from emp order by sal desc;
3)limit s,n
limit子句可以被用於強制select語句返回指定的記錄數。limit接受一個或兩個數字參數。參數必須是一個整數常量。如果給定兩個參數,第一個參數指定第一個返回記錄行的偏移量,第二參數指定返回記錄行的最大數目n。初始記錄行的偏移量是0(而不是1)。
(1)查看薪水最低的前5位員工信息
select * from emp order by sal limit 0,5;
óselect * from emp order by sal limit 5;
(2)查看第3到第7號員工信息
select * from emp limit 2,5;