Wordpress SQL:获取帖子类别和标签

时间:2018-01-15 22:01:52

标签: mysql sql wordpress tags

我想查询存储在MySQL数据库中的Wordpress数据,以获得带有列的结果:

  1. POST_ID
  2. 类别
  3. 逗号分隔的标签
  4. 预期产出:

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

    以下是我的尝试:

    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`)
    

    因此,我得到了我想要的列,包含预期的内容,但是我只获得了一行

    我做错了什么?

2 个答案:

答案 0 :(得分:1)

正如评论中所指出的,我包括了一个聚合函数,但没有" group by"子句。

现在这似乎有效(只添加了GROUP BY行):

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      |
+---------------+----------+----------------+
谢谢草莓!

答案 1 :(得分:1)

这是基于 Pierre 的代码,扩展为连接多个类别,以及包含没有类别或标签的帖子。

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