对于给定数据,SQL Query JOIN在同一个表上

时间:2017-11-25 12:11:12

标签: sql oracle join h2

我有以下表格和数据:

CREATE TABLE TEST_TABLE (
  ID NUMBER(6) NOT NULL,
  COMMON_SEQ NUMBER(22),
  NAME VARCHAR(20),
  CONSTRAINT PK_CONST PRIMARY KEY (ID)
);
INSERT INTO TEST_TABLE (ID, COMMON_SEQ, NAME) VALUES (1001, NULL, 'Michelle');
INSERT INTO TEST_TABLE (ID, COMMON_SEQ, NAME) VALUES (1002, NULL, 'Tiberius');
INSERT INTO TEST_TABLE (ID, COMMON_SEQ, NAME) VALUES (1003, NULL, 'Marigold');
INSERT INTO TEST_TABLE (ID, COMMON_SEQ, NAME) VALUES (1004, 999, 'Richmond');
INSERT INTO TEST_TABLE (ID, COMMON_SEQ, NAME) VALUES (1005, 999, 'Marianne');
INSERT INTO TEST_TABLE (ID, COMMON_SEQ, NAME) VALUES (1006, NULL, 'Valentin');
INSERT INTO TEST_TABLE (ID, COMMON_SEQ, NAME) VALUES (1007, 888, 'Juliette');
INSERT INTO TEST_TABLE (ID, COMMON_SEQ, NAME) VALUES (1008, NULL, 'Lawrence');

此表中的某些记录通过COMMON_SEQ的公共值相互关联(例如,999的COMMON_SEQ与Richmond和Marianne相关)。

如何根据给定的ID选择所有名称作为输入?

我尝试将表连接到自身(当COMMON_SEQ为null时正常工作)。此示例返回Michelle记录:

SELECT T.ID, T.COMMON_SEQ,T.NAME
FROM TEST_TABLE T 
LEFT JOIN TEST_TABLE T2 ON NOT T.COMMON_SEQ is NULL 
  AND T.COMMON_SEQ=T2.COMMON_SEQ AND T.ID<>T2.ID
WHERE T.ID=1001

但它没有带回ID 1004的2条记录。这个例子只返回里士满记录(但我还需要返回Marianne记录):

SELECT T.ID, T.COMMON_SEQ,T.NAME
FROM TEST_TABLE T 
LEFT JOIN TEST_TABLE T2 ON NOT T.COMMON_SEQ is NULL 
  AND T.COMMON_SEQ=T2.COMMON_SEQ AND T.ID<>T2.ID
WHERE T.ID=1004

当我只提供一个ID值(1004或1005)时,如何改进/重写查询以返回Richmond和Marianne记录?

2 个答案:

答案 0 :(得分:4)

您可以使用:

SELECT *
FROM TEST_TABLE t
WHERE COMMON_SEQ IN (SELECT COMMON_SEQ
                     FROM TEST_TABLE t1
                     WHERE t1.ID = 1004)
  OR t.ID = 1004;                  

<强> DBFiddle Demo

两次传递相同的参数以处理NULL中的COMMON_SEQ

答案 1 :(得分:2)

试试这个

 SELECT COALESCE (ty.id, tx.id) AS id,
        COALESCE (ty.common_seq, tx.common_seq) AS common_seq,
        COALESCE (ty.name, tx.name) AS name
  FROM test_table tx LEFT OUTER JOIN test_table ty
             ON (tx.common_seq = ty.common_seq)
 WHERE tx.ID = 1004;

有了这个,您可以避免使用IN或EXISTS,这可能会更高效。