开发者

How to get related items without SELECT each id

开发者 https://www.devze.com 2023-03-10 16:28 出处:网络
I have to do a database design for a Friend-Network. When I add someone as someone friend, I actually add their uniqueID to a table with two columns.

I have to do a database design for a Friend-Network. When I add someone as someone friend, I actually add their uniqueID to a table with two columns.

| USER 1 | USER 2 |

So when I want to known what are someone friends, I do a SELECT in this table looking for ID.

But the problem, is when I want to show the friend list i have to search all his friends, and after do a lookup for each ID looking for details. It just does not look right.

Is there a more efficie开发者_高级运维nt way to do it? Could I design my database? Is there any place where we can learn more about database design?


Your design seems fine to me. However look into JOINs which will help you get rid of nested queries to get info for the users. JOINs will allow you to get all the info about both users in one query and then you can loop through and print the list.

The query might become something like:

SELECT 
     u.name 
FROM 
     friends f 
     JOIN users s ON (u.id = f.user_id_2) 
WHERE 
     f.user_id_2 = 1234


I think you're on the right track given what you've said above. A many-to-many association table is the canonical way to what you're describing. It sounds like the issue might be in your query - you say you have to make multiple lookups. You should be able to write something like this

SELECT * FROM People p1
         INNER JOIN Friends f on p1.id = f.id1 and p2.id = f.id2
         INNER JOIN People p2 on p2.id = f.id2
       WHERE p1.id = 6123
0

精彩评论

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