php和mysql的关系,PHP和MySQL-有效处理多个一对多关系

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.

解决方案

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.

SELECT schedule.id, overrides.id, locations.id, locations.name

FROM schedule

JOIN overrides ON overrides.schedule_id = schedule.id

JOIN locations ON locations.override_id = overrides.id

ORDER BY schedule.id, overrides.id, locations.id

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 -

$last_schedule = 0;

$last_override = 0;

$schedules = array();

while ($row = mysql_fetch_array($query_result))

{

$schedule_id = $row[0];

$override_id = $row[1];

$location_id = $row[2];

$location_name = $row[3];

if ($schedule_id != $last_schedule)

{

$schedules[$schedule_id] = array();

}

if ($override_id != $last_override)

{

$schedules[$schedule_id][$override_id] = array();

}

$schedules[$schedule_id][$override_id][$location_id] = $location_name;

$last_schedule = $schedule_id;

$last_override = $override_id;

}

Quite primitive, I imagine your code will look different, but hopefully it makes some sense.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值