开发者

MySql and PHP - Get the top value in a "tree", based on a lower value

I really don't know how to word this, so the "similar questions" and searching are doing much good.

I've got a table of Users, and each User is assigned a "level" based on where they are in the org. chart. It's sales-based... so you have "Sellers", "Sales Managers","Regional Managers", etc. The way I set up the database is to have a join table with the user_id and the manager_user_id paired up. So a Seller with id 开发者_运维问答4 is paired with a Manager whose id is 12, and 12 is matched with a Regional Mgr whose id is 34, and so on.

What I'd like to do is get the top most Manager's information based on a the lower Seller's id. So in the example above, I input id #4 and get the info for user_id 34.

I know I could do a loop, and keep returning the manager_user_id until it returns no rows... but that would mean 5 separate queries. Is there a single query that could accomplish this?

If a similar question has been asked before, that would be great too. Thanks!


Not with the database structure you are describing. More full-featured DBMSs allow you to do recursive queries, but MySQL does not have this capability. You could write a stored procedure that does it, which allows you to get the topmost manager with a single SQL statement issued from your application (the logic for determining the topmost manager being handled by the DBMS).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜