1.SELECT 語法
1).SELECT 列名稱 FROM 表名稱
SELECT LastName,FirstName FROM Persons
2).SELECT * FROM 表名稱
mysql> select * from mytable;
3).Select+where條件
select Name,age from mytable where age >=20 and age <=25 addre = ‘gucheng’;
或select * from mytable where age >=20 and age <=25 addre = ‘gucheng’;
4).Select+where+like條件
select Name from mytable where Name like 'y%' or Name like 'n%';
或select Nam* from mytable where Name like 'y%';
或select Name from mytable where Name like '%ing%';
5).使用 Rlike 篩選已mny開頭的用戶(正則表達式)。
select Name from mytable where Name Rlike '^[MNY].*$';
6).使用 in 關鍵字,后面跟上一個列表
select Name from student where age in (18,20,25);
students 中有個字段課程(CID2)。查找出改字段,里面為空的字段的,學生姓名 Name
select Name from students where CID2 is null ;
查詢不為空就是要 is not null
is null 和 is not null可以實現判斷字段是否為空
7).limit 子句:用於顯示 結果的前 N 行
只顯示前3行
select * from students limit 3;
8).只顯示3行,從第5行開始計算
select * from students limit 3,5;
9).group by 子句 :
用於分組,比如把students 表的 學生 按照男女進行分組
select age,Gender from students group by gender
students 表中的字段 有個課程的字段 CID 求出該字段中,需要將課程的人數,大於等於2的顯示出來
10).having 子句
只能和group by 搭配使用,使用group by 分組之后,再用having 過濾
select CID from students where having CID >=2
11).多表查詢如mytable(name,sex,addre,job),mypersons(name,birth)表,已知name,求douzi的年紀,生日,地址。
select mytable.sex,mytable.addre ,mypersons.birth from mytable ,mypersons where mytable.name = mypersons.name;
12).多表查詢2個表中相同名稱的人。
Select * from mytable join mypersons on mytable.name=mypersons.name;
13).SQL UNION 實例
查詢2個表中相同字段下不同值
SELECT 列名 FROM 表名UNION SELECT 列名 FROM 表名 ORDER BY 列名;
SELECT country FROM Websites UNION SELECT country FROM apps ORDER BY country;
14).UNION all 輸出列名下所有值
SELECT 列名 FROM 表名UNION SELECT 列名 FROM 表名ORDER BY 列名;
SELECT country FROM Websites UNION ALL SELECT country FROM apps ORDER BY country;
15).帶有 WHERE 的 SQL UNION ALL
SELECT 列名, 列名 FROM 表名WHERE 列名='CN'UNION ALL SELECT 列名, 列名 FROM 表名WHERE 列名='CN'ORDER BY 列名;
SELECT country, name FROM Websites WHERE country='CN' UNION ALL SELECT country, app_name FROM apps WHERE country='CN' ORDER BY country;
16).匹配列前綴查詢
指匹配列值的開頭部分,如:查詢用戶名以feinik開頭的所有用戶
Select * from mytable where name like ‘jing%’;
17).MySQL 排序
我們需要對讀取的數據進行排序,我們就可以使用 MySQL 的 ORDER BY 子句來設定你想按哪個字段哪種方式來進行排序,再返回搜索結果。
使用 ASC 或 DESC 關鍵字來設置查詢結果是按升序或降序排列
SELECT * from 表名 ORDER BY 列名 ASC;
如SELECT * from runoob_tbl ORDER BY submission_date ASC;
18).MySQL GROUP BY 語句
GROUP BY 語句根據一個或多個列對結果集進行分組。
在分組的列上我們可以使用 COUNT, SUM, AVG,等函數。
使用 GROUP BY 語句 將數據表按名字進行分組,並統計每個人有多少條記錄:
Select name ,count(*) from mytable group by name;