문제
내 데이터베이스에 트리 구조를 저장하는 테이블이 있습니다. 관련 필드는 다음과 같습니다.
mytree (id, parentid, otherfields...)
나는 모든 잎 노드 (즉, 모든 레코드를 찾고 싶습니다. id
다른 레코드가 아닙니다 parentid
)
나는 이것을 시도했다 :
SELECT * FROM mytree WHERE `id` NOT IN (SELECT DISTINCT `parentid` FROM `mytree`)
그러나 그것은 빈 세트를 반환했습니다. 이상하게도 "Not"을 제거하면 모든 비 잎 노드 세트를 반환합니다.
누구든지 내가 어디에서 잘못 될지 볼 수 있습니까?
업데이트: 답변에 감사드립니다. 그들은 모두 정확하고 저를 위해 일했습니다. Daniel의 쿼리가 작동하지 않는 이유 (Null Thing)를 설명하기 때문에 Daniel의 경우를 받아 들였습니다.
해결책
하위 쿼리에 포함되어 있기 때문에 쿼리가 작동하지 않았습니다 NULL
. 다음의 약간의 수정은 나에게 효과가 있습니다.
SELECT * FROM `mytree` WHERE `id` NOT IN (
SELECT DISTINCT `parentid` FROM `mytree` WHERE `parentid` IS NOT NULL)
다른 팁
쿼리가 작동하지 않는 이유는 없습니다. 다음은 왼쪽 외부 조인 구문의 동일한 것이 있습니다.이 방법으로 시도해 보시겠습니까?
select a.*
from mytree a left outer join
mytree b on a.id = b.parentid
where b.parentid is null
SELECT * FROM mytree AS t1
LEFT JOIN mytree AS t2 ON t1.id=t2.parentid
WHERE t2.parentid IS NULL
id가 아닌 Mytree에서 * 선택 *
http://archives.postgresql.org/pgsql-sql/2005-10/msg00228.php
내 테이블 구조입니다
memberid MemberID joiningposition packagetype
RPM00000 NULL Root free
RPM71572 RPM00000 Left Royal
RPM323768 RPM00000 Right Royal
RPM715790 RPM71572 Left free
RPM323769 RPM71572 Right free
RPM715987 RPM323768 Left free
RPM323985 RPM323768 Right free
RPM733333 RPM323985 Right free
RPM324444 RPM715987 *emphasized text*Right Royal
--
ALTER procedure [dbo].[sunnypro]
as
DECLARE @pId varchar(40) = 'RPM00000';
Declare @Id int
set @Id=(select id from registration where childid=@pId)
begin
-- Recursive CTE
WITH R AS
(
SELECT
BU.DateofJoing,
BU.childid,
BU.joiningposition,
BU.packagetype
FROM registration AS BU
WHERE
BU.MemberID = @pId and
BU.joiningposition IN ('Left', 'Right')
or BU.packagetype in('Royal','Platinum','Majestic')
and BU.Id>@id
UNION All
-- Recursive part
SELECT
BU.DateofJoing,
BU.childid,
R.joiningposition,
BU.packagetype
FROM R
JOIN registration AS BU
ON BU.MemberID = R.childid
WHERE
BU.joiningposition IN ('Left', 'Right') and
BU.packagetype in('Royal','Platinum','Majestic')
and BU.Id>@id
)
INSERT INTO Wallatpayout
(childid
,packagetype
,joiningposition
,DateofJoing
,Total)
-- Final groups of nodes found
SELECT top 3
R.childid,
R.packagetype,
R.joiningposition,
R.DateofJoing,
Total = COUNT_BIG(*)
FROM R where R.packagetype in('Royal','Platinum','Majestic')
GROUP BY R.childid,
R.joiningposition,
R.DateofJoing,
R.packagetype
OPTION (MAXRECURSION 0);
end
제휴하지 않습니다 StackOverflow