sql查询查找包含同一Oracle表中其他记录的ID的记录

时间:2015-05-13 18:54:56

标签: sql oracle

我需要针对Oracle 11数据库运行SQL查询,该数据库将检索记录,其中一个记录本身在单独的列下具有值,这些列保存同一表中一个或多个其他记录的自动生成的ID。 / p>

因此,表中的记录看起来像这样:

| FOREIGN_PARTY_ID | ORG_NAME | RELATED_PARTY_ID1 | RELATED_PARTY_ID2 | ...
| 1001             | null     | null              | null              | ...
| 1002             | null     | null              | null              | ...
| 1003             | null     | null              | null              | ...
| 1004             | null     | null              | null              | ...
| 1005             | ABC, INC. | 1001             | 1002              | 1003      | 1004

1 个答案:

答案 0 :(得分:1)

此查询将返回表中的所有行,其中包含至少一个RELATED_PARTY_IDn字段中来自FOREIGN_PARTY_ID的自动生成的ID:

SELECT
  t.*, 
  t1.*, /* actually, you can specify only fields you need */
  t2.*, 
  ...,
  tn.*
FROM YOUR_TABLE_NAME t
LEFT JOIN YOUR_TABLE_NAME t1 ON t1.RELATED_PARTY_ID1 = t.FOREIGN_PARTY_ID
LEFT JOIN YOUR_TABLE_NAME t2 ON t2.RELATED_PARTY_ID2 = t.FOREIGN_PARTY_ID
...
LEFT JOIN YOUR_TABLE_NAME tn ON tn.RELATED_PARTY_IDn = t.FOREIGN_PARTY_ID
WHERE
    t1.FOREIGN_PARTY_ID IS NOT NULL 
 OR t2.FOREIGN_PARTY_ID IS NOT NULL 
 OR ...
 OR tn.FOREIGN_PARTY_ID IS NOT NULL 

如果您只想在EVERY RELATED_PARTY_IDn字段中获取包含您的ID的行,则可以OR条件更改WHERE条件中的AND.enabled = false