需要查询mysql中的多级营销

时间:2012-05-10 07:09:22

标签: php mysql

您好我需要在MySQL中查询我的PHP页面,我为表格设计提供数据:

tablename:tcustomers

Name, LeftID, RightID, Code
---------------------------
Arul    102      103     101
James   104      105     102
Alex    106      107     103
David   108      109     104
Sasi    110      111     105
Prem    112      113     106
Kumar   114      115     107

我需要的是当我在数据中传递arul代码即101时,我需要将他的左右两侧示例输出为

LEFT         Right
James        Alex
David        Prem
Sasi         Kumar

如果有人可以在不使用storedprocdure的情况下帮助我,那将非常有帮助,并提前感谢:)

1 个答案:

答案 0 :(得分:1)

如果你想要只有有限数量的左右元素答案,这是部分解决方案

这是一种可能性有3个右侧和3个左侧答案,条件Code = 101(Arul):

SELECT
    c.Name as NameRequested,
    l1.Name as NameLeft1,
    l2.Name as NameLeft2,
    l3.Name as NameLeft3,
    r1.Name as NameRight1,
    r2.Name as NameRight2,
    r3.Name as NameRight3
FROM tcustomers c
LEFT JOIN tcustomers l1 ON c.LeftID = l1.Code
LEFT JOIN tcustomers l2 ON l1.LeftID = l2.Code
LEFT JOIN tcustomers l3 ON l2.LeftID = l3.Code
LEFT JOIN tcustomers r1 ON c.RightID = r1.Code
LEFT JOIN tcustomers r2 ON r1.RightID = r2.Code
LEFT JOIN tcustomers r3 ON r2.RightID = r3.Code
WHERE
    l.Code = 101;

当然您可以轻松扩展您需要的答案数