简体   繁体   中英

How to select one item and array of items from other table in mysql?

Let's say I've got two tables:

Table1 (with objects):

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

Table2 (with schedule):

| 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         | 

First table defines mine objects, and there are only unique objects, second table defines schedule of the objects. Object can be scheduled on different dates, I mean there can be records with one object_id, but different dates.

I want to select data from these tables in that way:

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

How to query it?

You cannot select the records how you want. SQL returns a 1 level array, I do not think you can get it to return a multi level one. What you can do is to get the records and process them to get you what you desire.
You should run a command to select everything from the second table (no join necessary) then:

$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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM