I need to perform the following MySQL query in a Wordpress installation:
- Get the category IDs where the category name is "Oppskrifter".
- Get the child categories of all these IDs.
- Get the children of the resulting child categories (i.e. the children of 2. and the grandchildren of 1.).
I am trying to solve this using subqueries with aliases, but I am not able to make it work nor am I certain that this is the best way of doing it. Here is my current take:
SELECT * FROM
(
SELECT term_id AS oppskrifter_id
FROM wp_terms WHERE name = "Oppskrifter"
) AS R1,
(
SELECT * FROM wp_terms AS t
INNER JOIN wp_term_taxonomy AS tt
ON tt.term_id = t.term_id
WHERE tt.taxonomy = "category" AND tt.parent IN (R1)
) AS R2;
The first subquery works just fine by itself, but when introducing the second one it does not know what R1 is yet, thus I get the error ERROR 1054 (42S22): Unknown column 'R1' in 'having clause'. If I substitute R1 by the actual query, SELECT term_id AS oppskrifter_id FROM wp_terms WHERE name = "Oppskrifter" I get the error message ERROR 1060 (42S21): Duplicate column name 'term_id'.
What I was thinking to do here was to get the children (bullet point 2) in the second query and then do the exact same thing for the grandchildren using those results.
What are my options to solve this? What are the proper ways of doing it, both speed-wise and readability-wise?
R1refers multiple columns yet you are trying to searchtt.parentcolumn in collection of columns.