首页 > 解决方案 > 在Mysql中使用JOIN子句查询后合并结果

问题描述

我有两个这样的表:

产品

id | title 
-------------------------------
1 | Skirt
2 | Pants

产品缩略图

id | product_id   | image
-------------------------------
1 | 1             | pant.jpg
2 | 1             | shoes.png

当我想获得带有缩略图的产品时,我会这样查询:

SELECT p.*, pt.image FROM product p
LEFT JOIN product_thumbnail pt ON pt.product_id = p.id;

我期望的输出

[0]=> [
          [id] => 1
          [image] =>
          [ 
            [0] => pant.jpg
            [1] => shoes.jpg
          ]
      ]

[1]=> [
          [id] => 2
          [image] => null
      ]

但真正的输出

[0]=> [
          id => 1
          image => pant.jpg
      ]

[1]=> [
          id => 1
          image => shoes.jpg
      ]

[2]=> [
          id => 2
          image => shoes.jpg
      ] 

如您所见,有 2 个元素重复,所以我需要手动合并它,有什么方法可以更轻松地实现这一点?因为我的表有许多表比这更多地关联在一起,所以我使用 PHP,我使用 array_merge_recursive() 来合并它们,但如果这样做,我会在每个字段中得到重复值,如下所示:

[0]=> [
          [id] =>
              [
                [0] => 1
                [1] => 1
              ]

          [image] =>
              [
                [0] => pant.jpg
                [1] => shoes.jpg
              ]
      ]

这不是我想要的,谁能给我一个想法?

标签: phpmysqlsqldatabase

解决方案


考虑以下。我肯定可以更经济地编写代码,但希望你明白......

<?php

/*
DROP TABLE IF EXISTS product;

CREATE TABLE product
(id SERIAL PRIMARY KEY
,title VARCHAR(12) NOT NULL UNIQUE
);

INSERT INTO product VALUES
(1,'Hat'),
(2,'Shoe');

DROP TABLE IF EXISTS product_thumbnail;

CREATE TABLE product_thumbnail
(id SERIAL PRIMARY KEY
,product_id INT NOT NULL
,image VARCHAR(12) NOT NULL UNIQUE
);

INSERT INTO product_thumbnail VALUES
(1,1,'sombrero.jpg'),
(2,1,'stetson.png');

SELECT p.id
     , p.title
     , t.image
  FROM product p
  LEFT
  JOIN product_thumbnail t
    ON t.product_id = p.id;
+----+-------+--------------+
| id | title | image        |
+----+-------+--------------+
|  1 | Hat   | sombrero.jpg |
|  1 | Hat   | stetson.png  |
|  2 | Shoe  | NULL         |
+----+-------+--------------+
*/

require('path/to/connection/stateme.nts');

$query = "
SELECT p.id
     , p.title
     , t.image
  FROM product p
  LEFT
  JOIN product_thumbnail t
    ON t.product_id = p.id;
";

$result = mysqli_query($db,$query);

$old_array = array();

while($row = mysqli_fetch_assoc($result)){
    $old_array[] = $row;
}


$new_array = array();

foreach ($old_array as $row) {
   $new_array[$row['id']]['title'] = $row['title'];
   $new_array[$row['id']]['image'][] = $row['image'];
}

$new_array = array_values($new_array); // reindex


print_r($new_array);

?>

输出

Array
(
    [0] => Array
        (
            [title] => Hat
            [image] => Array
                (
                    [0] => sombrero.jpg
                    [1] => stetson.png
                )

        )

    [1] => Array
        (
            [title] => Shoe
            [image] => Array
                (
                    [0] => 
                )

        )

)

推荐阅读