php - 多层MySQL查询?

标签 php mysql codeigniter

我有两个表(条目和标签)和一个多对多链接表。现在,我正在查询以检索符合我条件的所有条目,并查询每个条目以检索标签。

有没有办法说,在第一个查询中通过新列将标签作为数组返回?

最佳答案

这个查询:

SELECT     e.id                               entry_id
,          GROUP_CONCAT(t.txt ORDER BY t.txt) tags
FROM       entry e
LEFT JOIN  entry_tag et
ON         e.id = et.entry_id
LEFT JOIN  tag t
ON         et.tag_id = t.id
GROUP BY   e.id

将以逗号分隔的列表形式返回标签​​。您可以阅读 GROUP_CONCAT 以获得更多选项:http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html#function_group-concat

在您的应用中,您应该能够很容易地将其扩展为数组。例如在 php 中,你可以使用 explode: http://php.net/manual/en/function.explode.php

如果您需要来自 tagentry_tag 表的更多属性,您可以添加更多的 GROUP_CONCAT 列,或者考虑一些序列化为您的数据设置格式(如 JSON)并在其上使用 GROUP_CONCAT,或者您可以简单地为每个条目返回多行并在应用程序中处理结果以将标签与条目保持在一起:

$sql = '
    SELECT     e.id                  entry_id
    ,          t.id                  tag_id
    ,          t.txt                 tag_text
    ,          t.published           tag_published
    FROM       entry e
    LEFT JOIN  entry_tag et
    ON         e.id = et.entry_id
    LEFT JOIN  tag t
    ON         et.tag_id = t.id
    ORDER BY   e.id
';        
$result = mysql_query($ql);
$entry_id = NULL;
$entry_rows = NULL;
while ($row = mysql_fetch_assoc($result)) {
    if ($entry_id != $row['entry_id']) {
        if (isset($entry_id)) {           //ok, found new entry
            process_entry($entry_rows);   //process the rows collected so far
        }
        $entry_id = $row['entry_id'];
        $entry_rows = array();
    }
    $entry_rows[] = $row;                 //store row for his entry for later processing
}
if (isset($entry_id)){                    //process the batch of rows for the last entry
    process_entry($entry_rows);           
}

关于php - 多层MySQL查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2307384/

相关文章:

php - 从CakePHP到外部PHP调用表单数据

php - 对于在后端使用 mysql 的网站,什么会被视为平均负载或高负载?

php - mysql。如何在没有 COALESCE 的情况下用结果集中的某些预定义值替换 NULL

javascript - 如何使用codeigniter在MYSQL数据库中使用数组索引上传文件

php - codeigniter 将数据库驱动程序调用扩展为未定义的方法 my_db_mysql_driver::select()

php/codeigniter firestore 更新给出错误 InvalidArgumentException 输入缺少所需的一个或多个必需的键

javascript - 发出关闭消息框 cookie

php - 需要帮助使用 php mysql 生成报告

php - 对mysql中的多个字段进行加权搜索的最佳方法?

php - 从数据库中转换乱码