---
title: "使用Oracle的minus时注意order by"
author: "ypluck"
date: "2008-10-24T09:54:16Z"
tags: []
categories: ["数据库"]
slug: "oracle-minus-order-by"
draft: false
lastmod: "2008-10-24T09:54:16Z"
id: 257278
url: "https://ypluck.iteye.com/blog/257278"
---

昨天发现一个很奇怪的现象，我在分页时的SQL明明是6条，结果确是意想不到的（是9条），我的SQL是这样的
```sql
select rownum,Page.* from(select id_item,itemname,id_itemclass,id_org from stm_list where id_item not in (select id_item from stm_exppsinfo where id_ptitem='P00002' and grpcode='200901' and IS_FENPEI='Y') and grpcode='200901' and id_ptitem='P00002' order by id_itemclass,id_org)Page where rownum<=66 MINUS select rownum,Page.* from(select id_item,itemname,id_itemclass,id_org from stm_list where id_item not in (select id_item from stm_exppsinfo where id_ptitem='P00002' and grpcode='200901' and IS_FENPEI='Y') and grpcode='200901' and id_ptitem='P00002' order by id_itemclass,id_org)Page where rownum<=60
```


查查了原因，原来是在使用order by的时候出问题了，本人的经验，在使用minus时同时又使用order by进行排序，这时候请加上第二个排序条件，而且这个排序的条件尽量不要重复，以免出现意想不到的结果，最好是主键。

总结：

1.oracle的minus是差集的意思
2.oracle的INTERSECT 是返回两个查询中都出现的记录
3.oracle的UNION 是返回两个查询的记录