来自同一个表的嵌套值

时间:2013-02-06 11:01:07

标签: sql

需要从同一个表中检索值,其中一列中的值用作不同记录中的父ID。这是在第三级完成的,这意味着一个记录中第一列的值用于第二列中的另一个记录,然后第二个记录中的第一列值用于另一个记录第二列。对于这个第三级嵌套,我使用了以下查询:

SELECT C1.CALLCATEGORYDESCR AS "First", 
       C2.CALLCATEGORYDESCR AS "Second",
       C3.CALLCATEGORYDESCR AS "Third" 
FROM CALLCAT C1
JOIN CALLCAT C2
ON C1.CALLCATEGORY = C2.parent_id
JOIN CALLCAT C3
ON C2.CALLCATEGORY = C3.PARENT_ID
WHERE C3.ACTIVE = 1

其中CALLCATEGORY是第一列,PARENT_ID是第二列。

此查询工作正常,我得到第三级嵌套的结果。但我需要查找仅嵌套在第二级的记录以及非嵌套的记录(其callcategory值不用作parent_id) 。 基本上我需要更多的查询第二级嵌套,没有嵌套,第三个输出列将具有NULL值,而在没有嵌套的情况下,第二和第三列将为NULL。

2 个答案:

答案 0 :(得分:0)

您可以使用Union

执行此操作
SELECT C1.CALLCATEGORYDESCR AS "First", 
       C2.CALLCATEGORYDESCR AS "Second",
       C3.CALLCATEGORYDESCR AS "Third" 
FROM CALLCAT C1
JOIN CALLCAT C2
ON C1.CALLCATEGORY = C2.parent_id
JOIN CALLCAT C3
ON C2.CALLCATEGORY = C3.PARENT_ID
WHERE C3.ACTIVE = 1

UNION

SELECT C1.CALLCATEGORYDESCR AS "First", 
       C2.CALLCATEGORYDESCR AS "Second",
       null AS "Third" 
FROM CALLCAT C1
JOIN CALLCAT C2
ON C1.CALLCATEGORY = C2.parent_id
WHERE C2.ACTIVE = 1 and not exists 
(select 1 from callcat where parent_id = C2.CALLCATEGORY)

UNION

SELECT C1.CALLCATEGORYDESCR AS "First", 
       null AS "Second",
       null AS "Third" 
FROM CALLCAT C1
WHERE C1.ACTIVE = 1 and not exists 
(select 1 from callcat where parent_id = C1.CALLCATEGORY)

答案 1 :(得分:0)

尝试左连接

SELECT C1.CALLCATEGORYDESCR AS "First", 
   C2.CALLCATEGORYDESCR AS "Second",
   C3.CALLCATEGORYDESCR AS "Third" 
FROM CALLCAT C1
LEFT JOIN CALLCAT C2
ON C1.CALLCATEGORY = C2.parent_id
LEFT JOIN CALLCAT C3
ON C2.CALLCATEGORY = C3.PARENT_ID
WHERE C3.ACTIVE = 1