Pie*_*tti 6 mysql sql tags wordpress
我想查询存储在 MySQL 数据库中的 Wordpress 数据,以获得带有列的结果:
预期输出:
+---------------+----------+----------------+
| post_id | category | tags |
|---------------+----------+----------------+
| 213 | news | tag1,tag2,tag3 |
+---------------+----------+----------------+
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的:
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`)
Run Code Online (Sandbox Code Playgroud)
结果,我得到了我想要的列,以及预期的内容,但我只得到了一行。
我究竟做错了什么?
正如评论中所指出的,我包含了一个聚合函数,但没有“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 |
+---------------+----------+----------------+
Run Code Online (Sandbox Code Playgroud)
谢谢草莓!