在codeigniter查询中将第二个表检索为子数组

时间:2010-08-16 15:08:37

标签: sql codeigniter join

我有两张桌子A& B和B与A有很多:1的关系。

当从A查询行时,我也希望将相应的B记录作为数组返回并从A添加到结果数组中,所以我最终得到这样的结果:

A-ROW
   field
   field
   B-ITEMS
      item1
      item2
      item3

使用一个查询(可能是一个连接?)是否有一种干净的方法可以执行此操作,或者我应该只对A中的id执行第二次B查询并将其添加到结果数组中?

3 个答案:

答案 0 :(得分:6)

将表B连接到表A会更有效。它不会为您提供所需形状的数据。但是您可以迭代此结果并将数据构建为所需的形状。

以下是一些代码来说明这个想法:

// Join table B on table A through a foreign key
$sql = 'select a.id, a.x, b.y
    from a
    left join b on b.a_id=a.id
    order by a.id';

// Execute query
$result = $this->db->query($sql)->result_array();

// Initialise desired result
$shaped_result = array();

// Loop through the SQL result creating the data in your desired shape
foreach ($result as $row)
{
    // The primary key of A
    $id = $row['id'];

    // Add a new result row for A if we have not come across this key before
    if (!array_key_exists($id, $shaped_result))
    {
        $shaped_result[$id] = array('id' => $id, 'x' => $row['x'], 'b_items' => array());
    }

    if ($row['y'] != null)
    {
        // Push B item onto sub array
        $shaped_result[$id]['b_items'][] = $row['y'];
    }
}

答案 1 :(得分:1)

“...只需对A上的id执行第二次B查询并将其添加到结果数组中......” - 这是正确的解决方案。 SQL不会理解嵌套数组结构。

答案 2 :(得分:1)

以Smandoli所说的为基础 -

单独运行辅助查询更有效,因为即使主表(A)上的行数据已更改,辅助表(B)上未更改的数据也会导致(MySQL)查询缓存命中,假设ID永远不会更改

这不一定适用于连接查询方法。

如果辅助表(B)有多个行与主表中的单个行相关联,则连接方法将获取主表(A)的重复数据,因此也会有更少的数据通过线路传输。

希望任何想要这样做(相对)常见类型的数据检索的人都会觉得这很有用。