开发者

Getting 5level relation with one mysql query

Thank u a lot for your answers beforehand. I need to make a such thing

I have a table friendship (id,user_id,friend_id,status,timestamp)

So lets say I am a user with user_id=43 and I am visiting a user with user_id=15

开发者_StackOverflow中文版

In the profile it should be a connection line of friendships

Let me describe ... lets say I have a friendship with user (user_id=3 and the user with user_id=3 is friend with user which profile I am visiting.

So on web site I will see

Connection

MyIcon->UserIcon(15)->UserIcon(3)->UserIcon(i am visiting)

And only in case when the friendship statuses for all are status=1...

Can anybody tell me how the query should look like?


With plain MySQL, there is no native way to do this. You have to either decide how deep you want to look, and use that amount of JOIN operations to see if you can 'reach' from one user id to the other, or you could give the community contributed Graph engine a whirl:

http://openquery.com/products/graph-engine

(this involves using a non-official binary AFAIK, perhaps it is already availble as a plug-in, but I am not sure aobut that)

With that engine, you can do it in a single simple query:

SELECT * FROM foo WHERE latch = 1 AND origid = 15 AND destid = 43;

And this would then return one row for each link you have to travel to reach from user 15 to user 43. You'd use the application code to display it nicely.


Had you modeled this as a Nested Set modeled hierarchy instead of the Adjacency List model which you have then this query would be trivial. As it is, you're looking at having to use recursion, which isn't natural to a relational database.

For some great information on modeling hierarchies, check out Joe Celko's book.


You might look at this answer to a question about recursive selection to see a hack you can do on the mySql side of things. It shows how to create a hierarchy for selection.

In mySql (ANSI SQL), there is no "native" way to perform such a query.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜