同一个表的内连接,某些值没有重复

问题描述 投票:0回答:1

我有一个简单的表(my_table):

id
10 真实
11 真实
12 真实
20
21
CREATE TABLE my_table (
  id INTEGER PRIMARY KEY,
  key BOOLEAN NOT NULL
);

INSERT INTO my_table VALUES (10, true);
INSERT INTO my_table VALUES (11, true);
INSERT INTO my_table VALUES (12, true);
INSERT INTO my_table VALUES (20, false);
INSERT INTO my_table VALUES (21, false);

当我执行时:

SELECT my_table_1.id,
       my_table_1.key,
       my_table_2.id,
       my_table_2.key
FROM my_table AS my_table_1
  INNER JOIN my_table AS my_table_2 
    ON my_table_1.id < my_table_2.id
      AND my_table_1.key = my_table_2.key

我收到了想要的结果(没有重复的内部连接):

my_table_1.id my_table_1.key my_table_2.id my_table_2.key
10 t 12 t
10 t 11 t
11 t 12 t
20 f 21 f

但现在我只想检查

id
等于 11 和 12 的值,方法是:

SELECT my_table_1.id,
       my_table_1.key,
       my_table_2.id,
       my_table_2.key
FROM my_table AS my_table_1
  INNER JOIN my_table AS my_table_2 
    ON my_table_1.id < my_table_2.id
      AND my_table_1.key = my_table_2.key
      AND my_table_1.id IN (11, 12)

而不是完整的结果:

my_table_1.id my_table_1.key my_table_2.id my_table_2.key
10 t 11 t
10 t 12 t
11 t 12 t

我得到了错误的部分结果:

my_table_1.id my_table_1.key my_table_2.id my_table_2.key
11 t 12 t

过了一段时间,我想出了如何解决这个问题并通过双

IN
获得完整的结果:

SELECT my_table_1.id,
       my_table_1.key,
       my_table_2.id,
       my_table_2.key
FROM my_table AS my_table_1
  INNER JOIN my_table AS my_table_2 
    ON my_table_1.id < my_table_2.id
      AND my_table_1.key = my_table_2.key
      AND (my_table_1.id IN (11, 12) OR my_table_2.id IN (11, 12))

这给了我正确的结果。

另一个带有

id IN (21)
的例子:

SELECT my_table_1.id,
       my_table_1.key,
       my_table_2.id,
       my_table_2.key
FROM my_table AS my_table_1
  INNER JOIN my_table AS my_table_2 
    ON my_table_1.id < my_table_2.id
      AND my_table_1.key = my_table_2.key
      AND (my_table_1.id IN (21) OR my_table_2.id IN (21))

给出正确的结果:

my_table_1.id my_table_1.key my_table_2.id my_table_2.key
20 f 21 f

如果没有第二个

IN
,我会得到一个不完整的空结果。

看来问题已经解决了,不是吗?
但我仍然有一个问题,我可以以任何方式改进这个查询吗?我真的不喜欢使用两次

IN

sql postgresql join inner-join
1个回答
-1
投票

我建议使用以下查询:

SELECT my_table_1.id, 
       my_table_1.key, 
       my_table_2.id, 
       my_table_2.key
FROM my_table AS my_table_1
INNER JOIN my_table AS my_table_2 
    ON my_table_1.id < my_table_2.id
    AND my_table_1.key = my_table_2.key
LEFT JOIN (SELECT id FROM my_table WHERE id IN (10, 11)) AS filter_table
    ON my_table_1.id = filter_table.id OR my_table_2.id = filter_table.id
WHERE filter_table.id IS NOT NULL;

希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.