1

需要从同一表中检索值,其中一列中的值用作不同记录中的父 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 值。

4

2 回答 2

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)
于 2013-02-06T11:08:40.877 回答
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
于 2013-02-06T11:11:56.837 回答