1

我有三张桌子:

product:
    id
    name

product_image:
    product_id
    url

product_detail:
    product_id
    _key
    value

我想做的就是在一个查询中获取有关特定产品的所有信息。我正在获取 group_concatenated 图像和详细信息,但分组有问题(我认为是这样)。有时我会得到双倍的图像。我的查询是:

   SELECT p.id, p.name,
GROUP_CONCAT(i.url ORDER BY i.id ASC SEPARATOR "{^sep^}") as imgs,
GROUP_CONCAT(d._key, "{^val^}", d.value ORDER BY d.id asc separator "{^sep^}") AS details
FROM product p
LEFT JOIN product_image i ON p.id = i.product_id
LEFT JOIN product_detail d ON p.id = d.product_id
WHERE p.id = ...
GROUP BY i.product_id, d.product_id 
ORDER BY p.id ASC LIMIT ...;

而且,顺便说一句,我使用“{^sep^}”作为分隔符,以便稍后分解(在 php 中)结果。我想确定,该 url(和详细信息)不会以错误的方式展开(例如,如果我使用“,”作为分隔符,并且某些 url 还包含“,”)。这是一个好方法吗?

4

1 回答 1

0

您应该按 p.id 和 p.name 分组。您还可以使用 DISTINCT:

SELECT p.id, p.name,
GROUP_CONCAT(i.url ORDER BY i.id ASC SEPARATOR "{^sep^}") as imgs,
GROUP_CONCAT(d._key, "{^val^}", d.value ORDER BY d.id asc separator "{^sep^}") AS details
FROM product p
LEFT JOIN product_image i ON p.id = i.product_id
LEFT JOIN product_detail d ON p.id = d.product_id
WHERE p.id = ...
GROUP BY p.id, p.name
ORDER BY p.id ASC LIMIT ...;

或者

SELECT DISTINCT p.id, p.name,
GROUP_CONCAT(i.url ORDER BY i.id ASC SEPARATOR "{^sep^}") as imgs,
GROUP_CONCAT(d._key, "{^val^}", d.value ORDER BY d.id asc separator "{^sep^}") AS details
FROM product p
LEFT JOIN product_image i ON p.id = i.product_id
LEFT JOIN product_detail d ON p.id = d.product_id
WHERE p.id = ...
GROUP BY i.product_id, d.product_id 
ORDER BY p.id ASC LIMIT ...;
于 2013-01-18T22:12:16.000 回答