SQL SELECT 语句

SELECT 语句用于从数据库中选取数据,选中的数据集合称为结果集。

 

1. SELECT 语法

SELECT column_name,column_name
FROM table_name;

SELECT * FROM table_name;

样本数据库

在本教程中,我们将使用 CodeBaoku 样本数据库。

下面是选自 "Websites" 表的数据:

+----+--------------+---------------------------+-------+---------+
| id | name         | url                       | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1  | Google       | https://www.google.cm/    | 1     | USA     |
| 2  | 淘宝          | https://www.taobao.com/   | 13    | CN      |
| 3  | 编程宝库      | http://www.codebaoku.com/ | 4689  | CN      |
| 4  | 微博          | http://weibo.com/         | 20    | CN      |
| 5  | Facebook     | https://www.facebook.com/ | 3     | USA     |
+----+--------------+---------------------------+-------+---------+

 

2. SELECT Column 范例

下面的 SQL 语句从 "Websites" 表中选取 "name" 和 "country" 列:

SELECT name,country FROM Websites;

执行结果:
+--------------+---------+
| name         | country |
+----+---------+---------+
| Google       | USA     |
| 淘宝          | CN      |
| 编程宝库      | CN      |
| 微博          |  CN     |
| Facebook     | USA     |
+--------------+---------+

 

3. SELECT * 范例

下面的 SQL 语句从 "Websites" 表中选取所有列:

SELECT * FROM Websites;

执行结果:
+----+--------------+---------------------------+-------+---------+
| id | name         | url                       | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1  | Google       | https://www.google.cm/    | 1     | USA     |
| 2  | 淘宝          | https://www.taobao.com/   | 13    | CN      |
| 3  | 编程宝库      | http://www.codebaoku.com/ | 4689  | CN      |
| 4  | 微博          | http://weibo.com/         | 20    | CN      |
| 5  | Facebook     | https://www.facebook.com/ | 3     | USA     |
+----+--------------+---------------------------+-------+---------+

SQL SELECT DISTINCT 语句:在一个表中,同一列可能会包含多个重复值,有时我们希望仅仅列出不同的值。SELECT DISTINCT 关键词用于返回唯一不同的值。SQL SELECT DISTINCT 语法:SELECT DISTINCT column_name,column_name FROM table_name。