1、從數(shù)據(jù)庫(kù)表中檢索信息 實(shí)際上,前面我們已經(jīng)用到了SELECT語(yǔ)句,它用來(lái)從數(shù)據(jù)庫(kù)表中檢索信息。
select語(yǔ)句格式一般為:
SELECT 檢索關(guān)鍵詞 FROM 被檢索的表 WHERE 檢索條件(可選)
以前所使用的“ * ”表示選擇所有的列。
下面繼續(xù)使用我們?cè)谏掀恼轮袆?chuàng)建的表mytable。
2、查詢所有數(shù)據(jù): mysql> select * from mytable;
+----------+------+------------+----------+
| name | sex | birth | birthaddr |
+----------+------+------------+--------+
| abccs |f | 1977-07-07 | china |
| mary |f | 1978-12-12 | usa |
| tom |m | 1970-09-02 | usa |
+----------+------+------------+----------+
3 row in set (0.00 sec)
3、修正錯(cuò)誤記錄: 假如tom的出生日期有錯(cuò)誤,應(yīng)該是1973-09-02,則可以用update語(yǔ)句來(lái)修正: mysql> update mytable set birth = "1973-09-02" where name = "tom";
再用2中的語(yǔ)句看看是否已更正過(guò)來(lái)。
4、選擇特定行 上面修改了tom的出生日期,我們可以選擇tom這一行來(lái)看看是否已經(jīng)有了變化:
mysql> select * from mytable where name = "tom";
+--------+------+------------+------------+
| name |sex | birth | birthaddr |
+--------+------+------------+------------+
| tom |m | 1973-09-02 | usa |
+--------+------+------------+------------+
1 row in set (0.06 sec)
上面WHERE的參數(shù)指定了檢索條件。我們還可以用組合條件來(lái)進(jìn)行查詢:
mysql> SELECT * FROM mytable WHERE sex = "f" AND birthaddr = "china";
+--------+------+------------+------------+
| name |sex | birth | birthaddr |
+--------+------+------------+------------+
| abccs |f | 1977-07-07 | china |
+--------+------+------------+------------+
1 row in set (0.06 sec)
5、 選擇特定列 假如你想查看表中的所有人的姓名,則可以這樣操作:
mysql> SELECT name FROM mytable;
+----------+
| name |
+----------+
| abccs |
| mary |
| tom |
+----------+
3 row in set (0.00 sec)
如果想列出姓名和性別兩列,則可以用逗號(hào)將關(guān)鍵詞name和birth分開(kāi): myaql> select name,birth from mytable;
6、對(duì)行進(jìn)行排序 我們可以對(duì)表中的記錄按生日大小進(jìn)行排序:
mysql> SELECT name, birth FROM mytable ORDER BY birth;
+----------+------------+
| name | birth |
+----------+------------+
| tom | 1973-09-02 |
| abccs | 1977-07-07 |
| mary | 1978-12-12 |
+----------+------------+
3 row in set (0.00 sec)
我們可以用DESC來(lái)進(jìn)行逆序排序:
mysql> SELECT name, birth FROM mytable ORDER BY birth DESC;
+----------+------------+
| name | birth |
+----------+------------+
| mary | 1978-12-12 |
| abccs | 1977-07-07 |
| tom | 1973-09-02 |
+----------+------------+
3 row in set (0.00 sec)
7、 行計(jì)數(shù) 數(shù)據(jù)庫(kù)經(jīng)常要統(tǒng)計(jì)一些數(shù)據(jù),如表中員工的數(shù)目,我們就要用到行計(jì)數(shù)函數(shù)COUNT()。COUNT()函數(shù)用于對(duì)非NULL結(jié)果的記錄進(jìn)行計(jì)數(shù):
mysql> SELECT COUNT(*) FROM mytable;
+----------+
| COUNT(*) |
+----------+
| 3 |
+----------+
1 row in set (0.06 sec)
員工中男女?dāng)?shù)量:
mysql> SELECT sex, COUNT(*) FROM mytable GROUP BY sex;
+------+----------+
| sex | COUNT(*) |
+------+----------+
| f | 2 |
| m | 1 |
+------+----------+
2 row in set (0.00 sec)
注意我們使用了GROUP BY對(duì)SEX進(jìn)行了分組。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com