[英]Echo all results from sql join when using group by
I have the following query which I run via PHP: 我有以下通过PHP运行的查询:
select
{$tableProducts}.*,
{$tableImages}.*
from {$tableProducts}
left join {$tableImages}
on {$tableImages}.product_id = {$tableProducts}.product_id
group by {$tableProducts}.product_id;
Each product (from product table) can have several images (in images table). 每个产品(来自产品表)可以具有多个图像(在图像表中)。 I loop through the results with a simple while statement: 我用一个简单的while语句遍历结果:
while($row = $results->fetch_object()) {
echo $row->product_name; // Product table
echo $row->image_src; // Image table
}
Problem: Only the first image of each product is printed, but I want to display all of them. 问题:仅打印每个产品的第一张图像,但是我想全部显示。 All images are printed if I remove the "order by" part, but then the product_name is printed once for each image (so if one product has three images, the product_name would be printed three times as well). 如果删除“ order by”部分,则将打印所有图像,但是每张图像都会对product_name进行一次打印(因此,如果一个产品包含三张图像,那么product_name也将被打印三遍)。
How do I best solve this? 我该如何最好地解决呢?
That's how GROUP BY
works. 这就是GROUP BY
工作方式。
If you want to get all images for all products, you can solve that (at least) 3 ways: 如果要获取所有产品的所有图像,则可以(至少)通过以下三种方法解决该问题:
1 : Do not use GROUP BY
, handle it in the loop, like: 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 : Use GROUP BY
& query all images with different statements within the loop. 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 : Use aggregate string functions to get all images for a product. 3 :使用聚合字符串函数获取产品的所有图像。 This is only works in special cases, f.ex. 仅在特殊情况下有效。 here, as URL cannot consist new lines, for example. 在这里,例如,URL不能包含换行符。
In MySQL
: 在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;
In PostgreSQL
: 在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;
In the loop: 在循环:
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.