从两个结果获得交集

时间:2014-03-04 17:35:10

标签: sql

SELECT DISTINCT utover.startnr, utover.navn, ovelse.navn
FROM utover, ovelse
WHERE ovelse.navn in (
SELECT DISTINCT ovelse.navn
FROM utover, deltakelse, ovelse
WHERE utover.navn = 'Carl Lewis'
AND deltakelse.utover = utover.startnr
AND deltakelse.ovelse = ovelse.navn
GROUP BY ovelse.navn, utover.startnr

INTERSECT

SELECT DISTINCT ovelse.navn
FROM utover, deltakelse, ovelse
WHERE utover.navn <> 'Carl Lewis'
AND deltakelse.ovelse = ovelse.navn
AND deltakelse.utover = utover.startnr
GROUP BY ovelse.navn, utover.startnr
);

嘿,我正试图找出那些将'Carl Lewis'作为对手的人(utover.navn)的名字。我要求'Carl Lewis'所在的练习(deltakelse.ovelse)与其他所有练习之间的交叉点的名称和ID。我应该得到一个答案,但我什么也得不到。有人有想法吗?

由于我不能回答自己,我只是在编辑这个。在这里,我得到的每个人都是'卡尔·刘易斯'的对手,但不是那个只有“卡尔·刘易斯”作为对手的“一个”。 希望我这样做是可以的

2 个答案:

答案 0 :(得分:0)

INTERSECT会返回两个查询中存在的所有值,但是您的第一个查询会选择utover.startnr,这在第二个查询中永远不会出现,因此您的结果集将始终为空。

答案 1 :(得分:0)

也许重新加入连接会帮助你看到问题。

SELECT utover.startnr, utover.navn
FROM utover
WHERE
    EXISTS (SELECT 1
        FROM
            (ovelse AS ovelse2 INNER JOIN deltakelse AS deltakelse2 ON
                deltakelse2.ovelse = ovelse2.navn
            ) INNER JOIN utover AS utover2 ON
                utover2.startnr = deltakelse2.utover
        WHERE
            ovelse2.navn = utover.navn AND
            utover2.navn = 'Carl Lewis'
    ) AND
    EXISTS (SELECT 1
        FROM
            (ovelse AS ovelse3 INNER JOIN deltakelse AS deltakelse3 ON
                deltakelse3.ovelse = ovelse3.navn
            ) INNER JOIN utover AS utover3 ON
                utover3.startnr = deltakelse3.utover
        WHERE
            ovelse3.navn = utover.navn AND
            utover3.navn <> 'Carl Lewis'
    )