select從表中選取數據時需要使用select語句,也就是隻從表中選出(select)必要數據的意思。通過(select)語句查詢並選取出必要數據的過程稱爲匹配查詢或或查詢(query)。
1、基本列的查詢:
--查詢一列或多列
select <列名>,<列名>,...
from <表名>;
--查詢全部的列
select *
from <表名>;
查詢多列時,需要使用逗號進行分隔,查詢結果中列的順序和select 子句中的順序相同 。使用星號進行全部查詢的話,就無法設定列的顯示順序,會按照表的順序進行顯示。
2、爲列設置別名:
select <列名> as <別名>,<列名> as <別名>,...
from <表名>;
--例子:
select student_id as id
from student;
select student_id as "學號"
from student;
爲列設置別名是,使用as關鍵字。別名可以使用中文,中文需要用雙引號(")括起來。
3、常數的查詢:
select '商品' as string, 38 as number, '2009-02-24' as date,product_id, product_name
from product;
第1列'商品' 是 字符串常數 ,第2 列38 是 數字常數 ,第3 列'2009-02-24' 是 日期常數,將與product_id列和product_name 列一起被查詢出來。結果如下:
+--------+--------+------------+------------+--------------+
| string | number | date | product_id | product_name |
+--------+--------+------------+------------+--------------+
| 商品 | 38 | 2009-02-24 | 001 | T恤 |
| 商品 | 38 | 2009-02-24 | 0004 | 菜刀 |
| 商品 | 38 | 2009-02-24 | 0005 | 高壓鍋 |
| 商品 | 38 | 2009-02-24 | 0006 | 叉子 |
| 商品 | 38 | 2009-02-24 | 0007 | 擦菜板 |
| 商品 | 38 | 2009-02-24 | 0008 | 圓珠筆 |
+--------+--------+------------+------------+--------------+
4、查詢結果刪除重複項:
select distinct <列名>
from <表名>;
示例:
--不刪除重複項:
select product_type
from product;
--查詢結果:
+--------------+
| product_type |
+--------------+
| 衣服 |
| 廚房用具 |
| 廚房用具 |
| 廚房用具 |
| 廚房用具 |
| 辦公用品 |
+--------------+
--刪除重複項:
select distinct product_type
from product;
--查詢結果:
+--------------+
| product_type |
+--------------+
| 衣服 |
| 廚房用具 |
| 辦公用品 |
+--------------+
distinct在使用時null也被視爲一類數據。
distinct也可以在多列之前使用,只能寫在第一個列之前。
select distinct <列名>,<列名>,...
from <表名>;
--例子
select distinct type,color,...
from clothe;
--將type和color同時相同的查詢記錄合併爲一條記錄
5、使用where選擇記錄
select 語句通 where子句 來指定查詢數據的條件, 在where子句中可以指定“某一列的值和這個字符串相等”或者“某一列的值大於 這個數字”等條件。where的位置是固定的,只能在from後面。
select <列名>,...
from <表名>
where <條件表達式>;
--例子1
select product_name,product_type
from product
where product_type='衣服';
--解釋:選擇product_type='衣服'的記錄,只顯示product_name,product_type兩列
--例子2
select product_name
from product
where product_type='衣服';
--解釋:選擇product_type='衣服'的記錄,只顯示product_name一列