[英]Echo all results from sql join when using group by
我有以下通過PHP運行的查詢:
select
{$tableProducts}.*,
{$tableImages}.*
from {$tableProducts}
left join {$tableImages}
on {$tableImages}.product_id = {$tableProducts}.product_id
group by {$tableProducts}.product_id;
每個產品(來自產品表)可以具有多個圖像(在圖像表中)。 我用一個簡單的while語句遍歷結果:
while($row = $results->fetch_object()) {
echo $row->product_name; // Product table
echo $row->image_src; // Image table
}
問題:僅打印每個產品的第一張圖像,但是我想全部顯示。 如果刪除“ order by”部分,則將打印所有圖像,但是每張圖像都會對product_name進行一次打印(因此,如果一個產品包含三張圖像,那么product_name也將被打印三遍)。
我該如何最好地解決呢?
這就是GROUP BY
工作方式。
如果要獲取所有產品的所有圖像,則可以(至少)通過以下三種方法解決該問題:
1 :不要使用GROUP BY
,而是在循環中處理它,例如:
$last_product = null;
while($row = $results->fetch_object()) {
if ($last_product !== $row->product_id) {
// new product starts here
$last_product = $row->product_id;
echo $row->product_name; // Product table
}
echo $row->image_src; // Image table
}
2 :使用GROUP BY
並在循環中查詢具有不同語句的所有圖像。
$products = <query products>;
while($row = $products->fetch_object()) {
echo $row->product_name; // Product table
$images = <query images for product in $row>;
while($row = $images->fetch_object()) {
echo $row->image_src; // Image table
}
}
3 :使用聚合字符串函數獲取產品的所有圖像。 僅在特殊情況下有效。 在這里,例如,URL不能包含換行符。
在MySQL
:
select
{$tableProducts}.*,
group_concat({$tableImages}.image_src SEPARATOR '\n') as image_srcs
from {$tableProducts}
left join {$tableImages}
on {$tableImages}.product_id = {$tableProducts}.product_id
group by {$tableProducts}.product_id;
在PostgreSQL
:
select
{$tableProducts}.*,
string_agg({$tableImages}.image_src, '\n') as image_srcs
from {$tableProducts}
left join {$tableImages}
on {$tableImages}.product_id = {$tableProducts}.product_id
group by {$tableProducts}.product_id;
在循環:
while($row = $products->fetch_object()) {
echo $row->product_name; // Product table
foreach (explode("\n", $row->image_srcs) as $image_src) {
echo $image_src; // Image table
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.