A more concise way of expressing this would be to use joins:
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"
;
Given the keys you have defined (or lack thereof), it would also be more efficient. See the two EXPLAIN analysis of your SQL and vs. the above:
Schema (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");
Query #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"
)
);
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
| --- | ----------- | ------ | ---------- | ---- | ------------- | --- | ------- | --- |
---- | -------- | ----------- |
| 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
Schema (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");
Query #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