从连接的两个表中获取数据

时间:2014-04-09 19:52:42

标签: 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;
    }   
}

控制器:

    $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>';
    ?>

3 个答案:

答案 0 :(得分:4)

按品牌订购您的查询,将所有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>';

答案 1 :(得分:0)

您永远不会在foreach循环中更新您的品牌信息。你应该构建一个数组数组:

$ data ['brand1'] =&gt; brand1的所有描述的数组    $ data ['brand2'] =&gt; brand2的所有描述的数组    [...]

答案 2 :(得分:-1)

像这样建立你的查询:

$query = "SELECT DISTINCT a.id AS aid, a.brand, b.descriptionColumn FROM brands a
            LEFT JOIN brand_desc b ON a.id = b.brand_id";