dpicx06888
dpicx06888
2011-01-31 12:50

如何处理使用PHP从SQL查询返回的树结构?

  • sqlite
  • php
  • mysql

This is a "theoretical" question.

I'm having trouble defining the question so please bear with me.

When you have several related tables in a database, for example a table that holds "users" and a table that holds "phones"

both "phones" and "users" have a column called "user_id"

select user_id,name,phone from users left outer join phones on phones.user_id = users.user_id;

the query will provide me with rows of all the users whether they have a phone or not.

If a user has several phones, his name will be returned in 2 rows as expected.

columns=>|user_id|name|phone|
row0 = > | 0 |fred|NULL|
row1 = > | 1 |paul|tlf1|
row2 = > | 1 |paul|tlf2|

the name "paul" in the case above is a necessary duplicate which in the RDMS's eye's is not a duplicate at all! It will then be handled by some server side scripting language, for example php.

How are these "necessary duplicates" actually handled in real websites or applications? as in, how are the row's "mapped" into some usable object model.

p.s. if you decide to post examples, post them for php,mysql,sqlite if possible.

edit:

Thank you for providing answers, each answer has interpreted the question differently and as such is different and correct in it's own way.

I have come to the conclusion that if round trips are expensive this will be the best way along with Jakob Nilsson-Ehle's solution, which was fitting for the theoretical question.

If round trips they are cheap, I will do separate selects for phones and users as 9000 suggests, if I need to show a single phone for every user, I will give a primary column to the phones and join it with the user select like Ollie Jones correctly suggests.

even though for real life applications I'm using 9000's answer, I think that for this unrealistic question Jakob Nilsson-Ehle's solution is most appropriate.

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

4条回答

为你推荐