我有三张桌子:
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也包含',')。这是一个好方法吗?
答案 0 :(得分: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 ...;