[英]Get data from two tables with join
我試圖從一個表中選擇一個品牌列表,從另一個表中選擇品牌描述。 一個品牌可以有多個描述。 我想擁有的是這樣的:
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>';
?>
按品牌訂購您的查詢,將所有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>';
您永遠不會在foreach循環中更新您的品牌信息。 您應該構建一個數組數組:
$ data ['brand1'] => brand1的所有描述的數組
$ data ['brand2'] => brand2的所有描述的數組
[...]
像這樣構建您的查詢:
$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";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.