0

假设我有两张桌子:

表1(带对象):

| object_id                          | int(11)       | NO   | PRI | NULL         | 
| owner_of_object_id                 | int(11)       | NO   | PRI | NULL         | 

表2(附时间表):

| object_id                          | int(11)       | NO   | PRI | NULL         | 
| reserved_from_date                 | date          | NO   | PRI | NULL         | 
| reserved_to_date                   | date          | NO   | PRI | NULL         | 
| reserved_to_id                     | int(11)       | NO   | PRI | NULL         | 

第一个表定义了我的对象,并且只有唯一的对象,第二个表定义了对象的时间表。对象可以安排在不同的日期,我的意思是可以有一个object_id的记录,但日期不同。

我想以这种方式从这些表中选择数据:

Array ( [0] => Array ( [object_id] = xxx, [reservations] = array( ALL RESERVATIONS ) ), [1] => next object) etc etc

如何查询呢?

4

1 回答 1

0

您无法根据需要选择记录。SQL 返回一个 1 级数组,我认为你不能让它返回一个多级数组。您可以做的是获取记录并处理它们以获得您想要的。
您应该运行命令从第二个表中选择所有内容(无需连接),然后:

$current_id = 0; $counter = 0;
foreach($records as $record) {
    //if this is not the first run and the current id is different then the db id then you should add this to your results array
    if($record->object_id != $current_id && $counter) {
        $results[] = array('object_id' => $current_id, 'reservations' => $_tmp_array);
        $_tmp_array = array();
    }
    $_tmp_array[] = $record;
    $counter++;
}
//final add to the results array
$results[] = array('object_id' => $current_id, 'reservations' => $_tmp_array);
于 2012-12-27T01:55:07.817 回答