我有一个具有Client
字段和Owner of the Client
字段的表,例如“ Amazon UK”和“ Amazon.com,Inc.”。分别。也可能发生的是,客户端的所有者也可以具有所有者,因此将出现在“客户端”字段中,并且可以一次又一次地发生,但最终将停止。
示例:
Client Owner of the Client
123 234
234 345
345 456
567 678
789 890
因此,我想知道递归SQL是否是最佳方法?还有没有办法让它出现在每个单独的列中,例如
Client Owner of Client Owner of Client Owner of Client
123 234 345 456
567 678 NULL NULL
789 890 NULL NULL
在此先感谢您的任何输入。
取决于深度,有多少所有者可以拥有另一个所有者...
如果想在1行上显示结果,最好使用一个简单的LEFT JOIN解决方案:
SELECT c1.* , c2.owner, c3.owner, c4.owner
FROM client_owner c1
left join client_owner c2 on c2.client = c1.owner
left join client_owner c3 on c3.client = c2.owner
left join client_owner c4 on c4.client = c3.owner
输出:
client owner owner owner owner
----------- ----------- ----------- ----------- -----------
123 234 345 456 NULL
234 345 456 NULL NULL
345 456 NULL NULL NULL
567 678 NULL NULL NULL
789 890 NULL NULL NULL