更简洁的表达方式是使用连接:
select t1.* from taxons t1
join taxons t2 on t1.name = "Babysicherungen & Schutzvorrichtungen" and t1.parent_id = t2.id and t2.name = "Babysicherheit"
join taxons t3 on t2.parent_id = t3.id and t3.name="Baby & Kleinkind"
;
鉴于您已定义(或缺少)键,它也会更有效。请参阅您的 SQL 和上面的两个 EXPLAIN 分析:
架构 (MySQL v5.7)
CREATE TABLE taxons (
id int NOT NULL PRIMARY KEY AUTO_INCREMENT,
parent_id int,
name varchar(255)
);
INSERT INTO taxons (parent_id, name) VALUES (NULL, "Baby & Kleinkind");
INSERT INTO taxons (parent_id, name) VALUES (1, "Babysicherheit");
INSERT INTO taxons (parent_id, name) VALUES (2, "Babysicherungen & Schutzvorrichtungen");
查询 #1
EXPLAIN SELECT *
FROM taxons
WHERE name = "Babysicherungen & Schutzvorrichtungen"
AND parent_id = (
SELECT id
FROM taxons
WHERE name = "Babysicherheit"
AND parent_id = (
SELECT id
FROM taxons
WHERE name = "Baby & Kleinkind"
)
);
|编号 |选择类型 |表|隔断 |类型 |可能的键 |关键 | key_len |参考 |行 |过滤 |额外 |
| --- | ------------ | ------ | ---------- | ---- | ------------- | --- | -------- | --- |
---- | -------- | ----------- |
| 1 | PRIMARY | taxons | | ALL | | | | | 3 | 33.33 | Using where |
| 2 | SUBQUERY | taxons | | ALL | | | | | 3 | 33.33 | Using where |
| 3 | SUBQUERY | taxons | | ALL | | | | | 3 | 33.33 | Using where |
---
View on DB Fiddle
架构 (MySQL v5.7)
CREATE TABLE taxons (
id int NOT NULL PRIMARY KEY AUTO_INCREMENT,
parent_id int,
name varchar(255)
);
INSERT INTO taxons (parent_id, name) VALUES (NULL, "Baby & Kleinkind");
INSERT INTO taxons (parent_id, name) VALUES (1, "Babysicherheit");
INSERT INTO taxons (parent_id, name) VALUES (2, "Babysicherungen & Schutzvorrichtungen");
查询 #1
EXPLAIN select t1.* from taxons t1
join taxons t2 on t1.name = "Babysicherungen & Schutzvorrichtungen" and t1.parent_id = t2.id and t2.name = "Babysicherheit"
join taxons t3 on t2.parent_id = t3.id and t3.name="Baby & Kleinkind"
;
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
| --- | ----------- | ----- | ---------- | ------ | ------------- | ------- | ------- | ----------------- | ---- | -------- | ----------- |
| 1 | SIMPLE | t1 | | ALL | | | | | 3 | 33.33 | Using where |
| 1 | SIMPLE | t2 | | eq_ref | PRIMARY | PRIMARY | 4 | test.t1.parent_id | 1 | 33.33 | Using where |
| 1 | SIMPLE | t3 | | eq_ref | PRIMARY | PRIMARY | 4 | test.t2.parent_id | 1 | 33.33 | Using where |
View on DB Fiddle