我是mysql的新手。
有这样一个计划:
-- auto-generated definition
create table category
(
id bigint not null auto_increment
primary key,
name varchar(255) not null
)
;
INSERT INTO `category` (`id`, `name`) VALUES (1, 'category1'), (2, 'category2'), (3, 'category3');
-- auto-generated definition
create table unit
(
id bigint not null auto_increment
primary key,
name varchar(128) not null
)
;
INSERT INTO `unit` (`id`, `name`)
VALUES
(1, 'unit1'),
(2, 'unit2'),
(3, 'unit3'),
(4, 'unit4'),
(5, 'unit5'),
(6, 'unit6'),
(7, 'unit7'),
(8, 'unit8'),
(9, 'unit9');
-- auto-generated definition
create table category_unit
(
id bigint not null auto_increment
primary key,
category_id bigint not null,
unit_id bigint not null,
constraint category_id_2
unique (category_id, unit_id)
)
;
create index category_id
on category_unit (category_id)
;
create index unit_id
on category_unit (unit_id)
;
INSERT INTO `category_unit` (`category_id`, `unit_id`)
VALUES
(1, 2),
(1, 3),
(1, 4),
(2, 4),
(2, 5),
(2, 6),
(3, 7),
(3, 3);
我创建了3个不同的查询:
1)
EXPLAIN SELECT
C.id,
C.name,
CU.name as units
FROM
category C
LEFT JOIN (
SELECT
CU.category_id,
GROUP_CONCAT(DISTINCT U.name ORDER BY U.name ASC SEPARATOR ', ') AS name
FROM category_unit CU
LEFT JOIN unit U ON U.id = CU.unit_id
GROUP BY CU.category_id
) as CU ON CU.category_id = C.id
WHERE
(CU.name LIKE "%unit2%" OR C.id LIKE "%unit2%" OR C.name LIKE "%unit2%")
GROUP BY
C.id;
这不是很好,因为它会扫描整个表格
2)
EXPLAIN SELECT
C.id,
C.name,
GROUP_CONCAT(DISTINCT U_current.name ORDER BY U_current.name ASC SEPARATOR ', ') AS name
FROM
category C
LEFT JOIN category_unit CU ON CU.category_id = C.id
LEFT JOIN unit U ON U.id = CU.unit_id
LEFT JOIN category_unit CU_current ON CU_current.category_id = C.id
LEFT JOIN unit U_current ON U_current.id = CU_current.unit_id
WHERE
(U.name LIKE "%unit2%" OR C.id LIKE "%unit2%" OR C.name LIKE "%unit2%")
GROUP BY
C.id;
这样做更好,但您必须再次选择相同的表格以选择所有分组的单位
3)
EXPLAIN SELECT
C.id,
C.name,
GROUP_CONCAT(DISTINCT U.name ORDER BY U.name ASC SEPARATOR ', ') AS name
FROM
category C
LEFT JOIN category_unit CU ON CU.category_id = C.id
LEFT JOIN unit U ON U.id = CU.unit_id
WHERE
C.id IN (
SELECT
C.id
FROM
category C
LEFT JOIN category_unit CU ON CU.category_id = C.id
LEFT JOIN unit U ON U.id = CU.unit_id
WHERE
(U.name LIKE "%unit2%" OR C.id LIKE "%unit2%" OR C.name LIKE "%unit2%")
)
GROUP BY
C.id;
在这里你必须进行2次相同的查询
P.S。 “WHERE”自动生成