Wordpress SQL: get post category and tags

我怕爱的太早我们不能终老 提交于 2020-02-22 06:59:06

问题


I want to query Wordpress data stored in a MySQL database, in order to get a result with columns:

  1. post_id
  2. category
  3. comma-separated tags

Expected output:

+---------------+----------+----------------+
| post_id       | category | tags           |
|---------------+----------+----------------+
| 213           | news     | tag1,tag2,tag3 |
+---------------+----------+----------------+

Here's what I have tried:

SELECT
    p.id,
    c.name,
    GROUP_CONCAT(t.`name`)
FROM wp_posts p
JOIN wp_term_relationships cr 
    on (p.`id`=cr.`object_id`)
JOIN wp_term_taxonomy ct 
    on (ct.`term_taxonomy_id`=cr.`term_taxonomy_id` and ct.`taxonomy`='category')
JOIN wp_terms c 
    on (ct.`term_id`=c.`term_id`)
JOIN wp_term_relationships tr 
    on (p.`id`=tr.`object_id`)
JOIN wp_term_taxonomy tt 
    on (tt.`term_taxonomy_id`=tr.`term_taxonomy_id` 
   and tt.`taxonomy`='post_tag')
JOIN wp_terms t 
    on (tt.`term_id`=t.`term_id`)

As a result, I get the columns I want, with the expected content, but I only get one row.

What am I doing wrong?


回答1:


As noted in the comments, I was including an aggregate function, but no "group by" clause.

Now this seems to work (just added the GROUP BY line):

SELECT
    p.id,
    p.post_name,
    c.name,
    GROUP_CONCAT(t.`name`)
FROM wp_posts p
JOIN wp_term_relationships cr
    on (p.`id`=cr.`object_id`)
JOIN wp_term_taxonomy ct
    on (ct.`term_taxonomy_id`=cr.`term_taxonomy_id`
    and ct.`taxonomy`='category')
JOIN wp_terms c on
    (ct.`term_id`=c.`term_id`)
JOIN wp_term_relationships tr
    on (p.`id`=tr.`object_id`)
JOIN wp_term_taxonomy tt
    on (tt.`term_taxonomy_id`=tr.`term_taxonomy_id`
    and tt.`taxonomy`='post_tag')
JOIN wp_terms t
    on (tt.`term_id`=t.`term_id`)
GROUP BY p.id


+---------------+----------+----------------+
| post_id       | category | tags           |
|---------------+----------+----------------+
| 213           | news     | tag1,tag2,tag3 |
+---------------+----------+----------------+
| 216           | whatever | tag2,tag3      |
+---------------+----------+----------------+

Thank you Strawberry!



来源:https://stackoverflow.com/questions/48271265/wordpress-sql-get-post-category-and-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!