DISTINCT没有消除重复记录 - 为什么?

时间:2014-11-12 12:07:29

标签: java sql eclipse db2

DISTINCT在DB2数据库查询

上没有正常工作
SELECT
    DISTINCT PF1
FROM
    (
        SELECT
                DISTINCT PF1
            FROM
                RELATIONS
        UNION
        SELECT
                DISTINCT PF2
            FROM
                RELATIONS
    )
WHERE
    PF1 NOT IN (
        SELECT
                DISTINCT NAME
            FROM
                REFERENCES
            WHERE
                TYPE = 'F'
    );

此查询以

的形式提供重复结果
C1:PROV
C1:PROV
WK:HEADER
WK:HEADER
WK:HEADER
etc

什么东西/设置导致这种异常行为?

FYI :相同的查询在另一台计算机的数据库中提供正确的结果。

被修改 这是表的结构

CREATE TABLE RELATIONS (
    PF1 VARCHAR(54) NOT NULL,
    PF1TXT VARCHAR(50),
    PF2 VARCHAR(54) NOT NULL,
    SEQ DOUBLE NOT NULL,
    PF2TXT VARCHAR(50),
  UNIQUE (PF1, SEQ, PF2)
);

CREATE TABLE REFERENCES (
    NAME1 VARCHAR(54) NOT NULL,
    NAMETXT VARCHAR(50) NOT NULL,
    NAME VARCHAR(54) NOT NULL,
    TYPE VARCHAR(1) NOT NULL,
    UNIQUE (NAME1, NAMETXT, NAME, TYPE) 
);

2 个答案:

答案 0 :(得分:2)

不确定,但您可以为派生表提供别名。在我的测试中它起作用了。

SELECT DISTINCT PF1 FROM (
    SELECT DISTINCT PF1 FROM RELATIONS
        UNION SELECT DISTINCT PF2 FROM RELATIONS
    )  as rel -- the name to derived table
WHERE PF1 NOT IN (
    SELECT DISTINCT NAME FROM REFERENCES
        WHERE TYPE = 'F');

答案 1 :(得分:2)

UNION应该已经消除重复。你可以稍微重新构建你的查询,它应该工作。我只做了REFS CTE,以防你的实际代码比这更复杂,以减少重复:

WITH REFS (NAME) AS (
    SELECT NAME
    FROM REFERENCES
    WHERE TYPE = 'F'
)

SELECT PF1
FROM RELATIONS
WHERE PF1 NOT IN (
    SELECT NAME FROM REFS
)

    UNION 

SELECT PF2
FROM RELATIONS
WHERE PF2 NOT IN (
    SELECT NAME FROM REFS
)

我在DB2 for LUW 9.7上测试了这个,它对我来说是正常的。