小编典典

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

sql

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

  1. post_id
  2. category
  3. tags

预期产量:

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

结果,我得到了想要的列以及期望的内容,但是 我只有一行

我究竟做错了什么?


阅读 143

收藏
2021-03-10

共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      |
+---------------+----------+----------------+

谢谢

2021-03-10