Search code examples
mysqlsqlwordpresswp-cli

combine two select statements (append columns)


I have 2 Wordpress database queries, the first shows all posts + categories. The second shows all posts + custom fields.

What I'm looking for is listing all posts + categories + custom fields

Query 1: list posts + categories

SELECT ID,
post_title,

(SELECT group_concat(wp_terms.name separator ", ") FROM wp_terms
INNER JOIN wp_term_taxonomy on wp_terms.term_id = 
wp_term_taxonomy.term_id
INNER JOIN wp_term_relationships wpr on wpr.term_taxonomy_id = 
wp_term_taxonomy.term_taxonomy_id
WHERE taxonomy="category" and wp_posts.ID = wpr.object_id ) AS 
"Categories"
FROM wp_posts WHERE post_type = "post" AND post_status = "publish"

+------+--------------------------------------+------------+
| ID   | post_title                           | Categories |
+------+--------------------------------------+------------+

Query 2: list posts + custom fields

SELECT ID, post_title, pm1.meta_value as "Amazon.com", pm2.meta_value 
as "Amazon.co.uk" FROM wp_posts
LEFT JOIN wp_postmeta pm1 ON ID = pm1.post_id AND 
pm1.meta_key = "Amazon.com"
LEFT JOIN wp_postmeta pm2 ON ID = pm2.post_id AND 
pm2.meta_key = "Amazon.co.uk"
WHERE post_type = "post" AND post_status = "publish"

+------+-----------------------+--------------+--------------+
| ID   | post_title            | Amazon.com   | Amazon.co.uk |
+------+-----------------------+--------------+--------------+

How can I combine the results so that I can list all posts + categories + custom fields?

+------+-------------+-------------+--------------+--------------+
| ID   | post_title  | Categories  | Amazon.com   | Amazon.co.uk |
+------+-------------+-------------+--------------+--------------+

Solution

  • Try using the following query:

    SELECT ID, post_title, pm1.meta_value as "Amazon.com", pm2.meta_value as "Amazon.co.uk" , 
                                            (SELECT group_concat(wp_terms.name separator ", ") FROM wp_terms
                                            INNER JOIN wp_term_taxonomy on wp_terms.term_id = 
                                            wp_term_taxonomy.term_id
                                            INNER JOIN wp_term_relationships wpr on wpr.term_taxonomy_id = 
                                            wp_term_taxonomy.term_taxonomy_id
                                            WHERE taxonomy="category" and wp_posts.ID = wpr.object_id ) AS "Categories"
    FROM wp_posts
    LEFT JOIN wp_postmeta pm1 ON ID = pm1.post_id AND 
    pm1.meta_key = "Amazon.com"
    LEFT JOIN wp_postmeta pm2 ON ID = pm2.post_id AND 
    pm2.meta_key = "Amazon.co.uk"
    WHERE post_type = "post" AND post_status = "publish"