使用 MySQL 在不同字段上使用多个 GROUP_CONCAT
我有一个这样的查询:
SELECT product.id,
GROUP_CONCAT(image.id) AS images_id,
GROUP_CONCAT(image.title) AS images_title,
GROUP_CONCAT(facet.id) AS facets_id
...
GROUP BY product.id
查询有效,但不符合预期,因为如果我有一个具有 5 个方面和 1 个图像的产品(假设 id=7 的图像),那么我会在“images_id”中得到类似的内容:
“7,7,7,7,7”
如果我有 2 个图像(7 和 3),那么我会得到类似的结果:
“7,7,7,7,7,3,3,3,3,3”
在方面我得到类似的东西:
“8,7,6,5,4,8,7,6,5,4”
我认为MySQL正在对查询返回的不同行进行某种类型的联合,然后连接所有内容。
我的预期结果是(对于最后一个示例):
images_id = "7,3"
facets_id = "8,7,6,5,4"
我可以在 GROUP_CONCAT 中使用 DISTINCT 来获得它,但是我还有另一个问题: 如果我有两张具有相同标题的图像,则省略其中一张,然后我会得到类似以下内容的信息:
images_id = "7,3,5"
images_title = "Title7and3,Title5"
所以我错过了 images_id 和 images_title 之间的关系。
有人知道是否可以在 MySQL 中进行此查询吗?
也许我把一切都复杂化了,却没有任何真正的好处。 由于性能原因,我尝试仅执行一个查询,但现在我不太确定执行两个查询是否更快(例如,一个用于选择方面,另一个用于图像)。
请解释您认为最好的解决方案是什么以及原因。
谢谢 !
I have a query like this:
SELECT product.id,
GROUP_CONCAT(image.id) AS images_id,
GROUP_CONCAT(image.title) AS images_title,
GROUP_CONCAT(facet.id) AS facets_id
...
GROUP BY product.id
And the query works, but not as expected, because if I have a product with 5 facets and 1 image (suppose an image with id=7), then I get something like this in "images_id":
"7,7,7,7,7"
If I have 2 images (7 and 3) then I get something like:
"7,7,7,7,7,3,3,3,3,3"
and in facets I get something like:
"8,7,6,5,4,8,7,6,5,4"
I think MySQL is making some type of union of the differents rows returned by the query, and then concatenating everything.
My expected result is (for the last example):
images_id = "7,3"
facets_id = "8,7,6,5,4"
I can obtain that using DISTINCT in the GROUP_CONCAT, but then I have another problem:
If I have two images with the same title, one of them is ommited, and then I get something like:
images_id = "7,3,5"
images_title = "Title7and3,Title5"
So I miss the relation between images_id and images_title.
Does somebody know if it's possible to make this query in MySQL?
Maybe I'm complicating everything without any real benefits.
I'm trying to execute only one query because performance, but now I'm not so sure if it's even faster to execute two queries (one for selecting the facets and another for the images for example).
Please explain what do you think is the best solution for this and why.
Thanks !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需添加
DISTINCT
。示例:
GROUP_CONCAT(DISTINCT image.id) AS images_id
Just add
DISTINCT
.Example:
GROUP_CONCAT(DISTINCT image.id) AS images_id
您需要分别获取每个组:
You'll need to get each group separately:
您可以仅添加 DISTINCT 关键字,您就会得到您想要的结果。
You can add just the DISTINCT keyword, you'll get your desire results.
如果问题是速度,那么只需选择所需的所有数据作为单独的行,并在应用程序中进行分组,即:
然后在应用程序中:
If the issue is speed, then it may be a lot faster to simply select all the data you need as separate rows, and do the grouping in the application, i.e.:
Then in the application: