Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在codeigniter查询中将第二个表作为子数组检索_Sql_Codeigniter_Join - Fatal编程技术网

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

Sql 在codeigniter查询中将第二个表作为子数组检索,sql,codeigniter,join,Sql,Codeigniter,Join,我有两张表A和B,B和A有很多:1的关系 查询A中的行时,我还希望将相应的B记录作为数组返回,并从A添加到结果数组中,因此我最终得到如下结果: A-ROW field field B-ITEMS item1 item2 item3 有没有一种干净的方法可以通过一个查询(可能是一个连接?)来实现这一点,或者我应该只对a的id执行第二次B查询并将其添加到结果数组中?“…只需对a的id执行第二次B查询并将其添加到结果数组中…”——这是正确的解决方

我有两张表A和B,B和A有很多:1的关系

查询A中的行时,我还希望将相应的B记录作为数组返回,并从A添加到结果数组中,因此我最终得到如下结果:

A-ROW
   field
   field
   B-ITEMS
      item1
      item2
      item3

有没有一种干净的方法可以通过一个查询(可能是一个连接?)来实现这一点,或者我应该只对a的id执行第二次B查询并将其添加到结果数组中?

“…只需对a的id执行第二次B查询并将其添加到结果数组中…”——这是正确的解决方案。SQL无法理解嵌套数组结构

将表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'];
    }
}

以斯曼多利的话为基础--

单独运行辅助查询效率更高,因为即使主表(A)上的行数据发生了更改,辅助表(B)上未更改的数据也会导致(MySQL)查询缓存命中(假设ID从未更改)

对于连接查询方法来说,这不一定是正确的

由于如果次表(B)中有多行与主表中的一行关联,则联接方法将获取主表(A)的重复数据,因此通过连接传输的数据也将减少


希望任何希望进行这种(相对而言)普通类型的数据检索的人都会发现这种方法很有用。

令人印象深刻的解决方案,并且画得很好。我目前正在尝试在我的应用程序中实现这一点,但我选择学习Datamapper(过于热心的版本)。如果不能实现,您的解决方案将非常适合我。如果每个人都有这样令人敬畏的、清晰的、深思熟虑的答案,那么在解决方案的布局和交付方面做得很好。