我有这些表:
颜色
colorId colorName
1 Blu
2 Green
3 Yellow
4 Red
颜色组
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
是否有可能有一个给出如下结果的 View :
bookId colorsGroupIds colorsGroupName
1 1,2 BG (Blu/Green), BY (Blu/Yellow)
2 2 BY (Blu/Yellow)
我尝试使用 group_by 来处理两个 View ,而第二个 View 连接第一个 View 的速度非常慢。 任何帮助将不胜感激。
<小时/>编辑。我尝试了你的 View 而不是我的 View ,但是 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
最佳答案
我用这些观点“解决”了:
colors_groups_view
SELECT
colors_groups.colorsGroupId,
colors_groups.colorsGroupName,
colors_groups_ids.colorId,
colors_groups_ids.order,
colors.colorName
FROM colors_groups
LEFT JOIN colors_groups_ids ON colors_groups_ids.colorGroupId=colors_groups.colorGroupId
LEFT JOIN colors ON colors_groups.colorId=colors.colorId
此 View 给出的结果如下:
colorsGroupId colorsGroupName colorId order colorName
1 BG 1 1 Blue
1 BG 2 2 Green
2 BY 1 1 Blue
2 BY 3 2 Yellow
然后:
books_view
SELECT
books.bookId,
(
SELECT
GROUP_CONCAT(
(
SELECT
CONCAT(colors_groups_view.colorsGroupName, " (", GROUP_CONCAT(colors_groups_view.colorName ORDER BY colors_groups_view.order ASC SEPARATOR "/"), ")", "") AS booksGroupsNames
FROM colors_groups_view
WHERE colors_groups_view.colorsGroupId=books_covers.colorsGroupId
GROUP BY colors_groups_view.colorsGroupId
)
SEPARATOR ", "
)
FROM books_covers
WHERE books_covers.bookId=books.bookId
GROUP BY books_covers.bookId
) AS booksGroupsNames
FROM books
由于第一个不进行任何 GROUP_BY 操作,因此速度非常快。我不知道是否可以避免这种情况,以及是否可以仅在一个查询中完成所有操作。
关于mysql - 连接多个 mysql 表并分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55007164/