【发布时间】:2019-07-27 04:15:44
【问题描述】:
我有这些表:
颜色
colorId colorName
1 Blu
2 Green
3 Yellow
4 Red
colors_groups
colorsGroupId colorsGroupName
1 BG
2 BY
3 RB
colors_groups_ids
colorsGroupId colorId colorOrder
1 1 1
1 2 2
2 1 1
2 2 3
3 4 1
3 1 2
书籍封面
bookId colorsGroupId
1 1
1 2
2 2
是否有可能得到这样的结果:
bookId colorsGroupIds colorsGroupName
1 1,2 BG (Blu/Green), BY (Blu/Yellow)
2 2 BY (Blu/Yellow)
我尝试使用 group_by 的两个视图,而加入第一个视图的第二个视图非常慢。 任何帮助将不胜感激。
编辑。我尝试了你的观点而不是我的观点,但是 SELECT 很慢,mysql 解释这样的查询:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 3320
2 DERIVED colors_groups ALL NULL NULL NULL NULL 3320 Using filesort
2 DERIVED colors_groups_ids ref colorsgroupid colorsgroupid 3 colorsgroupid 1
2 DERIVED colors eq_ref PRIMARY PRIMARY 2 colors.colorId 1 Using where
3220 是 color_groups 记录的数量。为什么要使用文件排序,每 3320 条记录获取两次?
这是查询:
SELECT
groups.colorsGroupId, groups.colorsGroupName,
GROUP_CONCAT(groups_ids.colorId ORDER BY groups_ids.order ASC) AS colors_ids,
GROUP_CONCAT(colors.colorName ORDER BY groups_ids.order ASC SEPARATOR "/") AS colors_names,
CONCAT(groups.colorsGroupName, " (", GROUP_CONCAT(colors.colorName ORDER BY groups_ids.order ASC SEPARATOR "/"), ")") AS colors_names_complete,
FROM colors_groups AS groups
JOIN colors_groups_ids group_ids
ON groups.colorsGroupId=group_ids.colorsGroupId
JOIN colors
ON group_ids.colorId=colors.colorId
GROUP BY groups.colorsGroupId, groups.colorsGroupName
【问题讨论】:
-
I tried我们能看到吗? -
我在尝试您的观点后编辑了答案
-
提示:不要将其保存为视图 - 你说“而不是”,但目前,您似乎没有查询
-
谢谢。保存为视图变化很大吗?
-
另外,一个 EXPLAIN 非常有用,不需要为所有相关表提供 SHOW CREATE TABLE 语句