我有一个用户系统,用户帐户可以拥有从属帐户。
为了表达这种关系,我有以下mysql表:
TABLE ACCOUNTS
ID
name
TABLE OWNEDACCOUNTS
accountID -> ACCOUNTS(ID)
ownerID -> ACCOUNTS(ID)
虽然这些表格并不明显,但这种关系只能达到两个层次:
帐户 - >子帐户 - >子子帐户
目前,我可以使用以下内容选择属于顶级帐户的所有子帐户:
SELECT a.ID
FROM accounts AS a
JOIN ownedAccounts AS o
ON o.accountID = a.ID
AND o.ownerID = ?
但是,我真正喜欢的是选择所有子帐户和属于单个顶级帐户的所有子帐户。我该怎么做?
先谢谢你的帮助
答案 0 :(得分:0)
Select ...
From accounts AS a
Join ownedAccounts AS o
On o.accountID = a.ID
Join accounts AS owner1
On owner1.ID = o.ownerID
Left Join ownedAccounts AS o2
On o2.accountID = owner1.ID
Left Join accounts As owner2
On owner2.ID = o2.ownerID
Where o.ownerID = ?
答案 1 :(得分:0)
这应列出您拥有的每个帐户,以及它的子和子潜艇的计数。希望这是一个很好的起点。
SELECT a.ID, count(sub.accountID), count(subsub.accountID)
FROM accounts AS a
LEFT JOIN ownedAccounts AS sub ON sub.ownerID = a.ID
LEFT JOIN ownedAccounts AS subsub ON subsub.ownerID = sub.accountID