mysql distinct 使用方法及实例介绍

时间:2016-06-01
mysql distinct 语句用于过滤查询结果中多余的重复记录,本文章通过一个简单的实例向码农介绍mysql distinct语句的使用方法,需要的码农可以参考一下本文章的distinct实例。

先给出本文章需要使用到的数据表:

mysql> select * from Employee;
+------+------------+-----------+-----------+-------------+
| id   | first_name | last_name | city      | description |
+------+------------+-----------+-----------+-------------+
|    1 | Jason      | Martin    | Toronto   | Programmer  |
|    2 | Alison     | Mathews   | Vancouver | Tester      |
|    3 | James      | Smith     | Vancouver | Tester      |
|    4 | Celia      | Rice      | Vancouver | Manager     |
|    5 | Robert     | Black     | Vancouver | Tester      |
|    6 | Linda      | Green     | New York  | Tester      |
|    7 | David      | Larry     | New York  | Manager     |
|    8 | James      | Cat       | Vancouver | Tester      |
+------+------------+-----------+-----------+-------------+
8 rows in set (0.00 sec)

比如我们要查询这张表中不同的city的具体的值,此时可以使用mysql distinct语句实现:

mysql> SELECT DISTINCT city FROM Employee;
+-----------+
| city      |
+-----------+
| Toronto   |
| Vancouver |
| New York  |
+-----------+
3 rows in set (0.00 sec)

注意mysqldistinct语句必须放在开头,下面写会报mysql错误:

mysql> SELECT id,DISTINCT city FROM Employee;

下面写法是正确的:

mysql> SELECT DISTINCT city id,FROM Employee;