wordpress-sql:get-post-category和tags

woobm2wo  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(341)

我想查询存储在mysql数据库中的wordpress数据,以便得到包含以下列的结果:
邮政编码
类别
逗号分隔标记
预期产量:

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

结果,我得到了我想要的列,以及预期的内容,但是我只得到了一行。
我做错什么了?

a9wyjsp7

a9wyjsp71#

正如在评论中指出的,我包括了一个聚合函数,但没有“groupby”子句。
现在这似乎奏效了(刚刚添加了 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      |
+---------------+----------+----------------+

谢谢你草莓!

相关问题