在《用MySQL創建數據庫和數據庫表》文章中,我們如何創建一個數據庫和數據庫表,並知道如何向數據庫表中添加記錄。 那麼我們如何從數據庫表中檢索數據呢?
1、從數據庫表中檢索信息
實際上,前面我們已經用到了SELECT語句,它用來從數據庫表中檢索信息。
select語句格式一般為:
SELECT 檢索關鍵詞 FROM 被檢索的表 WHERE 檢索條件(可選)
以前所使用的“ * ”表示選擇所有的列。下面繼續使用我們在上篇文章中創建的表mytable。
2、查詢所有數據:
3、修正錯誤記錄:
假如tom的出生日期有錯誤,應該是1973-09-02,則可以用update語句來修正: mysql> update mytable set birth = "1973-09-02" where name = "tom"; 再用2中的語句看看是否已更正過來。
4、選擇特定行
上面修改了tom的出生日期,我們可以選擇tom這一行來看看是否已經有了變化:
mysql> select * from mytable where name = "tom"; +--------+------+------------+------------+ | name |sex | birth | birthaddr | +--------+------+------------+------------+ | tom |m | 1973-09-02 | usa | +--------+------+------------+------------+ 1 row in set (0.06 sec)
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)
mysql> SELECT name FROM mytable; +----------+ | name | +----------+ | abccs | | mary | | tom | +----------+ 3 row in set (0.00 sec)
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)
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)
mysql> SELECT COUNT(*) FROM mytable; +----------+ | COUNT(*) | +----------+ | 3 | +----------+ 1 row in set (0.06 sec) 員工中男女數量: mysql> SELECT sex, COUNT(*) FROM mytable GROUP BY sex; +------+----------+ | sex | COUNT(*) | +------+----------+ | f | 2 | | m | 1 | +------+----------+ 2 row in set (0.00 sec)