繁体   English   中英

使用group by时回显sql join的所有结果

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM