oracle的distinct用法是可以过滤结果集中的重复行,确保“select”子句中返回指定的一列或多列的值是唯一的。其语法为“select distinct 列1,列2,列3... from 表名”,“distinct”会对返回的结果集进行排序,可以和“order by”结合使用,提高效率。
select distinct可以用来过滤结果集中的重复行,确保select子句中返回指定的一列或多列的值是唯一的。本文将为大家带来select distinct的具体用法。
oracle select distinct用法
select distinct语句的语法如下:
select distinct
column_1fromtable_name;
在上面语法中,table_name表的column_1列中的值将进行比较以过滤重复项。
要根据多列检索唯一数据,只需要在select子句中指定列的列表,如下所示:
select distinct column_1, column_2,...fromtable_name;
在此语法中,column_1,column_2和column_n中的值的组合用于确定数据的唯一性。
distinct子句只能在select语句中使用。
请注意,在oracle中distinct和unique没有区别,二者为同义词,distinct遵循ansi标准,unique是oracle特定的用法,从移植角度考虑,使用遵循ansi标准的distinct是一个更好的选择。
oracle distinct示例
下面来看看如何使用select distinct来看看它是如何工作的一些例子。
1. oracle distinct简单的例子
以下是一个table表
字段1 字段2id name1 a2 b3 c4 c5 b
如果想用一条语句查询得到name不重复的所有数据,那就必须使用distinct去掉多余的重复记录。所以首先输入:
select *, count(distinct name) from table group by name
然后我们再输入:
id name count(distinct name)
得到结果:
1 a 12 b 13 c 1
2. oracle distinct在一列上应用的例子
以下示例检索所有联系人的名字:
select first_namefrom contactsorder by first_name;
执行上面查询语句,得到以下结果:
该查询返回了319行,表示联系人(contacts)表有319行。
要获得唯一的联系人名字,可以将distinct关键字添加到上面的select语句中,如下所示:
该查询返回了302行,表示联系人(contacts)表有17行是重复的,它们已经被过滤了。
2. oracle distinct应用多列示例
看下面的order_items表,表的结构如下:
以下语句从order_items表中选择不同的产品id和数量:
selectdistinct product_id,quantityfromorder_itemsorder by product_id;
执行上面查询语句,得到以下结果
在此示例中,product_id和quantity列的值都用于评估结果集中行的唯一性。
3. oracle distinct和null
distinct将null值视为重复值。如果使用select distinct语句从具有多个null值的列中查询数据,则结果集只包含一个null值。
请参阅示例数据库中的locations表,结构如下所示:
以下语句从state列中检索具有多个null值的数据:
select distinct statefrom locationsorder by state nulls first;
执行上面示例代码,得到以下结果:
正如上图所看到的,只返回一个null值。
以上就是oracle distinct的用法是什么的详细内容。