PHP MySQL:如何从图像中检索与项目 ID 关联的所有图像 table
PHP MySQL: How to retrieve all images associated to an item id from images table
所以我有两个 table。
项目table:
+---------+-----------+
| item_id | item_name |
+---------+-----------+
| 1 | Item One |
| 2 | Item Two |
+---------+-----------+
图片 table:
+---------+----------------------+
| item_id | item_image |
+---------+----------------------+
| 1 | clofr9ohuvex5cxeyrfm |
| 1 | slnorjbqfd2x7ks0marp |
| 1 | oomkjtomvasklx9be4sq |
| 2 | um8donrpeuvfrmqb7qt |
| 2 | lowcvoaijxniiqdj5eoe |
| 2 | qwxfartcsdyusw4lrngi |
+---------+----------------------+
我的 php 代码获取项目列表及其关联图像:
$itemsQuery = $db->prepare("
SELECT *
FROM items a,item_images b
WHERE a.item_id = b.item_id
");
$itemsQuery->execute();
$items = $itemsQuery->fetchAll(PDO::FETCH_ASSOC);
var_dump($items);
我得到了 6 个结果,而不是 2 个。
我想要的是根据 item_id.
显示 "items table" 中存在的 2 个项目及其来自 "images table" 的关联图像
我可以查询 "items table" 并循环遍历它以再次查询数据库以获取图像。但是我怎样才能在一次数据库调用中完成呢?
您可以使用 GROUP_CONCAT
获取 MySQL 将第二个 table 中的所有值分组到一个列中:
SELECT
a.*, GROUP_CONCAT(b.item_image) AS item_images
FROM
items a,item_images b
WHERE
a.item_id = b.item_id
GROUP BY
a.item_id
结果将是一个名为 item_images
的键,其中包含 item
的每个 item_image
,由 ,
:
分隔
um8donrpeuvfrmqb7qt,lowcvoaijxniiqdj5eoe,qwxfartcsdyusw4lrngi
然后,如果您希望将其用作数组,则可以在 PHP 端使用 explode
。
所以我有两个 table。
项目table:
+---------+-----------+
| item_id | item_name |
+---------+-----------+
| 1 | Item One |
| 2 | Item Two |
+---------+-----------+
图片 table:
+---------+----------------------+
| item_id | item_image |
+---------+----------------------+
| 1 | clofr9ohuvex5cxeyrfm |
| 1 | slnorjbqfd2x7ks0marp |
| 1 | oomkjtomvasklx9be4sq |
| 2 | um8donrpeuvfrmqb7qt |
| 2 | lowcvoaijxniiqdj5eoe |
| 2 | qwxfartcsdyusw4lrngi |
+---------+----------------------+
我的 php 代码获取项目列表及其关联图像:
$itemsQuery = $db->prepare("
SELECT *
FROM items a,item_images b
WHERE a.item_id = b.item_id
");
$itemsQuery->execute();
$items = $itemsQuery->fetchAll(PDO::FETCH_ASSOC);
var_dump($items);
我得到了 6 个结果,而不是 2 个。
我想要的是根据 item_id.
显示 "items table" 中存在的 2 个项目及其来自 "images table" 的关联图像我可以查询 "items table" 并循环遍历它以再次查询数据库以获取图像。但是我怎样才能在一次数据库调用中完成呢?
您可以使用 GROUP_CONCAT
获取 MySQL 将第二个 table 中的所有值分组到一个列中:
SELECT
a.*, GROUP_CONCAT(b.item_image) AS item_images
FROM
items a,item_images b
WHERE
a.item_id = b.item_id
GROUP BY
a.item_id
结果将是一个名为 item_images
的键,其中包含 item
的每个 item_image
,由 ,
:
um8donrpeuvfrmqb7qt,lowcvoaijxniiqdj5eoe,qwxfartcsdyusw4lrngi
然后,如果您希望将其用作数组,则可以在 PHP 端使用 explode
。