PHP 和 MySQL - 高效处理多个一对多关系
我正在寻求一些有关使用 MySQL 和 PHP 检索和显示数据的最佳方法的建议。
我有 3 个表,都是一对多关系,如下所示:
每个 SCHEDULE 有许多 OVERRIDES,每个覆盖有许多 LOCATIONS。我想检索这些数据,以便可以将其全部显示在单个 PHP 页面上,例如列出我的时间表。在每个计划中列出“覆盖”,并在每个覆盖中列出“位置”。
选项1 - 最好的方法是进行 3 个单独的 SQL 查询,然后将它们写入 PHP 对象吗?然后我可以迭代每个数组并检查父数组上的匹配项。
选项 2 - 我对连接考虑了很多,但是执行两个右连接将为所有 3 个表中的每个入口返回一行。
任何想法和意见将不胜感激。
最好的问候,本。
I am seeking some advice on the best way to retrieve and display my data using MySQL and PHP.
I have 3 tables, all 1 to many relationships as follows:
Each SCHEDULE has many OVERRIDES and each override has many LOCATIONS. I would like to retrieve this data so that it can all be displayed on a single PHP page e.g. list out my SCHEDULES. Within each schedule list the OVERRIDES, and within each override list the LOCATIONS.
Option1 - Is the best way to do this make 3 separate SQL queries and then write these to a PHP object? I could then iterate through each array and check for a match on the parent array.
Option 2 - I have thought quite a bit about joins however doing two right joins will return me a row for every entrance in all 3 tables.
Any thoughts and comments would be appreciated.
Best regards, Ben.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您确实想要每条数据,则无论您如何操作,都将检索相同数量的行。最好在一次查询中获得所有信息。
通过像这样对结果进行排序,您可以迭代结果集,并在 Scheduleid 更改时转到下一个计划,并在 locationid 更改时转到下一个位置。
编辑:如何将此数据转换为 3 维数组的可能示例 -
非常原始,我想您的代码看起来会有所不同,但希望它有意义。
If you really want every piece of data, you're going to be retrieving the same number of rows, no matter how you do it. Best to get it all in one query.
By ordering the results like this, you can iterate through the result set and move on to the next schedule whenever the scheduleid changes, and the next location when the locationid changes.
Edit: a possible example of how to turn this data into a 3-dimensional array -
Quite primitive, I imagine your code will look different, but hopefully it makes some sense.