php - 在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
]
]
这不是我想要的,谁能给我一个想法?
解决方案
考虑以下。我肯定可以更经济地编写代码,但希望你明白......
<?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] =>
)
)
)
推荐阅读
- vba - 使用 VBA、Selenium 和 Chrome 检查文件是否完全下载
- html - 使用绝对位置和粘性
- r - 使用 dplyr::summarize 和 seq_along 时出错
- image - 在粘贴到 Word 之前减小图像大小
- mysql - mysql客户端在使用脚本运行时打印帮助消息,但直接在shell中运行良好
- sql - 在 postgres 表中查找前 n 个“未使用的值”
- python - XHR 响应不断被取消
- swift - 如何将我的 API 密钥存储在我的 iOS 应用程序中,以便我可以将我的应用程序发布到 App Store?
- android - HttpURLConnection.inputStream 空(InputStream 到 Bitmap)
- tensorflow - Dense(1,activation='sigmoid') 的输出,是二元分类问题的概率 y=1 还是 y=0?