2012-12-27 22 views
0

比方說,我有兩個表:如何從mysql中的其他表中選擇一個項目和數組的項目?

表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 

如何查詢呢?

+0

什麼是你想怎麼辦?如果你只是想加入它們,你可以使用JOIN命令(INNER JOIN等) – kennypu

+0

我想獲得這些特定類型的數組作爲php返回。 – pawel

+0

這很遺憾,但是你不能把這樣的數組當作你的迴應。最好你可以得到將是: 'Array([0] => Array([object_id] => xxx,[reserved_from_date] => xxx,[reserved_to_date] => xxx))' –

回答

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); 
相關問題