Oracle 专题
专题目录
您的位置:database > Oracle专题 > Oracle Distinct子句
Oracle Distinct子句
作者:--    发布时间:2019-11-20

在本教程中将学习如何使用oracle select distinct语句从表中查询不同(过滤相同值)的数据。

oracle select distinct语句简介

select语句中使用distinct子句来过滤结果集中的重复行。它确保在select子句中返回指定的一列或多列的值是唯一的。

以下说明了select distinct语句的语法:

select distinct
  column_1
from
  table_name;

在上面语法中,table_name表的column_1列中的值将进行比较以过滤重复项。

要根据多列检索唯一数据,只需要在select子句中指定列的列表,如下所示:

select
    distinct column_1,
    column_2,
        ...
from
    table_name;

在此语法中,column_1column_2column_n中的值的组合用于确定数据的唯一性。

distinct子句只能在select语句中使用。

请注意,distinct不是sql标准的unique的同义词。总是使用distinct而不使用unique是一个好的习惯。

oracle distinct示例

下面来看看如何使用select distinct来看看它是如何工作的一些例子。

1. oracle distinct在一列上应用的示例

查看示例数据库中的联系人(contacts)表:

以下示例检索所有联系人的名字:

select first_name
from contacts
order by first_name;

执行上面查询语句,得到以下结果 -

该查询返回了319行,表示联系人(contacts)表有319行。

要获得唯一的联系人名字,可以将distinct关键字添加到上面的select语句中,如下所示:

select distinct first_name
from contacts
order by first_name;

执行上面查询语句,得到以下结果 -

该查询返回了302行,表示联系人(contacts)表有17行是重复的,它们已经被过滤了。

2. oracle distinct应用多列示例

看下面的order_items表,表的结构如下:

以下语句从order_items表中选择不同的产品id和数量:

select
    distinct product_id,
    quantity
from
    order_items
order by product_id;

执行上面查询语句,得到以下结果 -

在此示例中,product_idquantity列的值都用于评估结果集中行的唯一性。

3. oracle distinct和null

distinctnull值视为重复值。如果使用select distinct语句从具有多个null值的列中查询数据,则结果集只包含一个null值。

请参阅示例数据库中的locations表,结构如下所示 -

以下语句从state列中检索具有多个null值的数据:

select distinct state
from locations
order by state nulls first;

执行上面示例代码,得到以下结果 -

正如上图所看到的,只返回一个null值。

在本教程中,您已学习如何使用select distinct语句来获取基于一列或多列的过滤获取唯一数据。


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册