MySQL: Using JOIN statement in a subqery

Revious :

Joins can be formulated in an explicit syntax ([INNER|LEFT|OUTER|..] JOIN... ON...) or specifying the conditions in the WHERE statement.

How can I refer to a table called in the external FROM statement and JOIN it in the subquery?

In this case I'm referring to the table with the alias p

SELECT 
    p.id,
    p.post_title,
    (SELECT 
            GROUP_CONCAT(DISTINCT wp_terms.name
                    SEPARATOR ',')
        FROM
            p
                JOIN
            wp_term_relationships ON (p.id = wp_term_relationships.object_id)
                LEFT JOIN
            wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
                LEFT JOIN
            wp_terms ON (wp_terms.term_id = wp_term_taxonomy.term_id)
                AND wp_term_taxonomy.taxonomy IN ('post_tag' , 'category'))
FROM
    `post_senza_revisioni` p
WHERE
    p.post_type = 'post'
        AND p.post_status = 'publish'
        AND p.post_parent = 0
GROUP BY id , post_title
Gordon Linoff :

I'm pretty sure you want a correlated subquery:

SELECT p.id, p.post_title,
       (SELECT GROUP_CONCAT(DISTINCT wp_terms.nameSEPARATOR ',')
        FROM wp_term_relationships tr
             wp_term_taxonomy tt
             ON tr.term_taxonomy_id = tt.term_taxonomy_id LEFT JOIN
              wp_terms t
              ON t.term_id = tt.term_id AND
                 tt.taxonomy IN ('post_tag' , 'category'))
        WHERE p.id = r.object_id
       )
FROM `post_senza_revisioni` p
WHERE p.post_type = 'post' AND
      p.post_status = 'publish' AND
      p.post_parent = 0;

I doubt the GROUP BY is needed in the outer query, so I removed it. If you do have duplicate id values in the p table, then you can add it back in -- although that suggests that id is a really bad name for the column.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=402035&siteId=1