如何在不使用DISTINCT和UNIQUE关键字的情况下获取唯一记录?

时间:2015-10-19 12:54:29

标签: sql oracle

PFB我没有DISTINCT或UNIQUE关键字的SQL查询,

SELECT CLAIM.CLAIM_ID,
CLAIM.ASSESSMENT_UNIT_ID,
HOUSEHOLD_MEMBER.ASSESSMENT_UNIT_MEM_ID,
PERSON.PERSON_ID
FROM CLAIM,
  AWARD,
  AWARD_MEMBER,
  HOUSEHOLD_MEMBER,
  PERSON,
  CONDITIONALITY_GROUP
WHERE CLAIM.CLAIM_ID              = AWARD.CLAIM_ID
AND AWARD.AWARD_ID                = AWARD_MEMBER.AWARD_ID
AND AWARD_MEMBER.HH_MEMBER_ID     = HOUSEHOLD_MEMBER.HH_MEMBER_ID
AND HOUSEHOLD_MEMBER.PERSON_ID    = PERSON.PERSON_ID
AND HOUSEHOLD_MEMBER.HH_MEMBER_ID = CONDITIONALITY_GROUP.HH_MEMBER_ID;

及以下是上述查询的结果

CLAIM_ID    ASSESSMENT_UNIT_ID  ASSESSMENT_UNIT_MEM_ID  PERSON_ID
5000000002  5000000002           1000004                1000004
5000000002  5000000002           1000004                1000004
5000000002  5000000002           1000003                1000003
5000000002  5000000002           1000003                1000003

在独特或独特的帮助下,问题得到解决,但它会影响查询的性能,请让我们知道,如何以另一种方式?

提前感谢您的帮助:)

2 个答案:

答案 0 :(得分:0)

做这样的事情(假设所有数据类型都是整数)。

这将首先为数据添加空行。但正如您所做的那样union,它将删除重复项。然后通过执行minus空行来删除重复项。

SELECT CLAIM.CLAIM_ID,
CLAIM.ASSESSMENT_UNIT_ID,
HOUSEHOLD_MEMBER.ASSESSMENT_UNIT_MEM_ID,
PERSON.PERSON_ID
FROM CLAIM,
AWARD,
AWARD_MEMBER,
HOUSEHOLD_MEMBER,
PERSON,
CONDITIONALITY_GROUP
WHERE CLAIM.CLAIM_ID              = AWARD.CLAIM_ID
AND AWARD.AWARD_ID                = AWARD_MEMBER.AWARD_ID
AND AWARD_MEMBER.HH_MEMBER_ID     = HOUSEHOLD_MEMBER.HH_MEMBER_ID
AND HOUSEHOLD_MEMBER.PERSON_ID    = PERSON.PERSON_ID
AND HOUSEHOLD_MEMBER.HH_MEMBER_ID = CONDITIONALITY_GROUP.HH_MEMBER_ID

union
select null,null,null,null from dual

minus

select null,null,null,null from dual

我尝试了这个查询,并没有给出任何重复。

(select 1,1,1,1 from dual union all
select 1,1,1,1 from dual union all
select 1,1,2,2 from dual union all
select 1,1,2,2 from dual)
union
select null,null,null,null from dual
minus
select null,null,null,null from dual

输出

1   1   1   1
1   1   2   2    

答案 1 :(得分:0)

要提高性能,请在where子句中包含的列上创建索引。例如,要在声明表中的CLAIM_ID列上创建索引,请使用:

create index idx_claimid_claim on CLAIM(CLAIM_ID)

您可能希望根据每列中的数据创建位图索引或b树索引。