【发布时间】:2013-02-17 06:47:07
【问题描述】:
问题
我应该如何进行查询以获得此结果?
我应该为数据库表使用不同的结构吗?
详情
我想从 3 个表中获取结果:
+------------------------------+-------------------+
| courses | id | <-------+
| | name | |
| | | |
+------------------------------+-------------------+ |
| sections | id | <-------|----------+
| | course_id | <- FK(courses.id) |
| | name | |
+------------------------------+-------------------| |
| resources | id | |
| | section_id | <- FK(sections.id)-+
| | name |
+------------------------------+-------------------+
我想将结果存储在这样的 PHP 数组中:
Array
(
[courses] => Array
(
[id] => 1
[name] => course 1
[sections] => Array
(
[0] => Array
(
[id] => 1
[course_id] => 1
[name] => course 1 section 1
[resources] => Array
(
[0] => Array
(
[id] => 1
[section_id] => 1
[name] => resource 1
)
)
)
)
)
)
编辑
我做了什么:
$cources = DB::query(Database::SELECT,
'select * from courses')->execute($db,false)[0]; // Get all courses as array
foreach($courses as &$course) {
$sections = DB::query(Database::SELECT,
'select * from sections where course_id = '.$courses['id']);
$course['sections'] = $sections;
foreach($course['sections'] as &§ion) {
$resources = DB::query(...); // Get array of resources
$section['resources'] = $resources;
}
}
【问题讨论】:
-
优化什么查询?你没有附上。您无法从 MySQL 获得多维结果。
-
我用 PHP 代码更新了问题
标签: php mysql database scalability