php - 通过连接从两个表中获取数据

标签 php mysql codeigniter

我正在尝试从一张表中选择品牌列表,并从另一张表中选择品牌描述。一个品牌可以有不止一种描述。我想要的是这样的:

Brand1
-brand1 description 1
-brand1 description 2
...etc

我现在拥有的:

Brand1
-brand1 description1
-brand1 description2
Brand1
-brand1 description1
-brand1 description2

模型函数:

function get_brand_desc() {
    $query = "SELECT a.id AS aid, a.brand, b.* FROM brands a
                LEFT JOIN brand_desc b ON a.id = b.brand_id";
    $q = $this->db->query($query);

    if($q->num_rows() > 0) 
    {
        foreach($q->result() as $descs)
        {
            $data[] = $descs;
        }
        return $data;
    }else{
        return false;
    }   
}

Controller :

    $admin_data['descs'] = $this->admin_model->get_brand_desc();

查看:

<?php
        echo '<ul>';
            foreach($descs as $desc) {
                echo '<li>';
                echo '<p>'.$desc->brand.'</p>';
                echo '<p>'.$desc->description.'</p>';
                echo '</li>';
            }
        echo '</ul>';
    ?>

最佳答案

按品牌排序您的查询,这会将所有 brand_desc 行组合在一起。因此,您的查询如下所示:

SELECT
    a.id AS aid,
    a.brand,
    b.* 
FROM 
    brands a
LEFT JOIN 
    brand_desc b ON 
        a.id = b.brand_id
ORDER BY 
    a.brand

现在,当您循环显示项目时,您将有几行重复品牌名称 -- 每个品牌描述。与其将此查询视为为您提供品牌列表,不如将其视为为您提供所有品牌描述的列表。因此,当您输出它时,您必须定义分组。

    echo '<ul>';
        $currentBrand = false;
        foreach($descs as $desc) {
            if ($currentBrand != $desc->brand) {
                if ($currentBrand !== false)
                    echo '</li>'; // if there was a brand LI open, close it
                echo '<li>'; // open a new LI for this new brand
                echo '<p>'.$desc->brand.'</p>';
                $currentBrand  = $desc->brand;
            }
            echo '<p>'.$desc->description.'</p>';
        }
    echo '</li>'; // closing out the brand that is left hanging open at the end
    echo '</ul>';

关于php - 通过连接从两个表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22972670/

相关文章:

php - 正则表达式将字符串末尾与单词匹配

php - 如何在一次 ajax 调用中返回 html 代码和 php 值

php - 跨 Azure Cosmos 中的多个集合查询记录

PHP 表单 - 使用一个或多个复选框更新数据库行

mysql - 什么 Amazon AWS AMI for web.py, mysql

php - JavaScript 或 PHP 中的宏?

mysql - 更改 MySQL 查询关键字的顺序?

php - 计算时差时的错误结果

php - 如何使用两个日期选择器从我的数据库获取数据。代码点火器

php - 如何删除 Codeigniter 下拉列表中的索引号?