【问题标题】:How to select one item and array of items from other table in mysql?如何从mysql中的其他表中选择一个项目和项目数组?
【发布时间】:2012-12-27 09:55:07
【问题描述】:

假设我有两张桌子:

Table1(带对象):

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

Table2(附时间表):

| 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

如何查询?

【问题讨论】:

  • 你想做什么?如果你只是想加入他们,你可以使用 JOIN 命令(INNER JOIN 等)
  • 我想得到这些特殊类型的数组作为 php 返回。
  • 很遗憾,但您无法得到这样的数组作为响应。你能得到的最好的将是:Array([0] => Array( [object_id] => xxx, [reserved_from_date] => xxx, [reserved_to_date] => xxx ))
  • 但是您可以很容易地将其映射到您实际需要的结构。

标签: php mysql


【解决方案1】:

您无法根据需要选择记录。 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);

【讨论】:

    猜你喜欢
    • 2023-01-09
    • 2021-12-14
    • 1970-01-01
    • 2019-12-17
    • 2011-10-17
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多