选择与众不同的区别

时间:2013-12-22 10:42:01

标签: sql oracle select

我有这张表columns_tab

INDEX_OWNER     INDEX_NAME           TEXT
------------------------------------------------------------------------
DUMMY           PK_FUL_REQUEST       CUSTOMERID, ID, INSTITUTIONID
NIR             PK_FUL_REQUEST       CUSTOMERID, ID, INSTITUTIONID
NIR             IX_REQUEST_HASH      CUSTOMERID, HASH_KEY, INSTITUTIONID
DUMMY           UQ_REQUEST_HASH      CUSTOMERID, HASH_KEY, INSTITUTIONID

我想得到text列相等的行,但index_name不相等。

我可以用2个相同的表来做,但是我可以用一个表吗?

预期结果是:

    INDEX_OWNER     INDEX_NAME           TEXT
------------------------------------------------------------------------
NIR             IX_REQUEST_HASH      CUSTOMERID, HASH_KEY, INSTITUTIONID
DUMMY           UQ_REQUEST_HASH      CUSTOMERID, HASH_KEY, INSTITUTIONID

可以通过

来实现对它的查询
select index_owner, index_name, text
  from columns_tab a, columns_tab b
 where a.text = b.text
   and a.index_name != b.index_name

我想在没有从同一张桌子中选择两次的情况下实现它。

2 个答案:

答案 0 :(得分:1)

你走了:

select owner, index_name, text
  from (select t.*,
               count(*) over(partition by text, index_name) both_match,
               count(*) over(partition by text) text_match
          from COLUMNS_TAB t)
 where text_match > 1
   and both_match = 1;

但必须指出的是,如果你在性能方面两次避免查询表,那么我的方法不一定会表现得更好。您应该比较两个查询的实际数据。

答案 1 :(得分:0)

另一个答案:

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE columns_tab ( INDEX_OWNER,     INDEX_NAME,           TEXT ) AS
          SELECT 'DUMMY', 'PK_FUL_REQUEST',  'CUSTOMERID, ID, INSTITUTIONID' FROM DUAL
UNION ALL SELECT 'NIR',   'PK_FUL_REQUEST',  'CUSTOMERID, ID, INSTITUTIONID' FROM DUAL
UNION ALL SELECT 'NIR',   'IX_REQUEST_HASH', 'CUSTOMERID, HASH_KEY, INSTITUTIONID' FROM DUAL
UNION ALL SELECT 'DUMMY', 'UQ_REQUEST_HASH', 'CUSTOMERID, HASH_KEY, INSTITUTIONID' FROM DUAL;

查询1

WITH prev_next AS (
  SELECT t.*,
         LAG( index_name  ) OVER ( PARTITION BY text ORDER BY index_name ) AS p_name,
         LEAD( index_name ) OVER ( PARTITION BY text ORDER BY index_name ) AS n_name
  FROM   columns_tab t
)
SELECT index_owner,
       index_name,
       text
FROM   prev_next
WHERE  index_name <> p_name
OR     index_name <> n_name

<强> Results

| INDEX_OWNER |      INDEX_NAME |                                TEXT |
|-------------|-----------------|-------------------------------------|
|         NIR | IX_REQUEST_HASH | CUSTOMERID, HASH_KEY, INSTITUTIONID |
|       DUMMY | UQ_REQUEST_HASH | CUSTOMERID, HASH_KEY, INSTITUTIONID |