我遇到自定义Wordpress MySQL查询的问题。我的情况是这样的:我有关于帖子的常规帖子类型'post'和自定义帖子类型''authors',有关作者的信息。 “作者”的帖子类型包含所有作者,但并非所有作者都需要作为帖子的作者。
每个帖子(类型'post'和'author')都有一个带有作者确切名称的自定义分类(例如“John Smith”)。帖子类型“作者”为作者的名字和姓氏提供了额外的自定义元值(因为它们可能变得复杂,并且更容易按姓氏,名字排序)。
现在我正在尝试选择发布帖子的所有作者,计算他们的帖子数量并显示与他们的名字相关的元值。我不确定如何从一个帖子类型('post')交叉引用分类法,而meta值在另一行中形成另一个('author')。
我想要的是什么:
John Smith John Smith 10
到目前为止我得到了什么:
John Smith 10 John
John Smith 10 Smith
我坚持下面的查询。任何帮助将不胜感激!
SELECT
N, C, meta_value
FROM
(SELECT
t.name AS N, count(*) AS C
FROM
wp_2_posts p
INNER JOIN wp_2_term_relationships AS tr ON p.ID=tr.object_id
INNER JOIN wp_2_term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
INNER JOIN wp_2_terms AS t ON tt.term_id = t.term_id
WHERE 1=1
AND tt.taxonomy = 'myauthor'
AND p.post_type = 'post'
AND p.post_status = 'publish'
GROUP BY
N
ORDER BY
C DESC) AS x
INNER JOIN wp_2_posts p2
INNER JOIN wp_2_term_relationships AS tr2 ON p2.ID=tr2.object_id
INNER JOIN wp_2_term_taxonomy AS tt2 ON tr2.term_taxonomy_id = tt2.term_taxonomy_id
INNER JOIN wp_2_terms AS t2 ON tt2.term_id = t2.term_id
INNER JOIN wp_2_postmeta AS m2 ON m2.post_id = p2.ID
WHERE 1=1
AND post_type = 'author'
AND t2.name = x.N
AND (m2.meta_key = 'lastname' OR m2.meta_key = 'firstname')
答案 0 :(得分:0)
这是一个相当不合理的解决方案,关于如何改进它的任何想法?
SELECT
N, C, m2.meta_value AS L, m3.meta_value AS F
FROM
(SELECT
t.name AS N, count(*) AS C
FROM
wp_2_posts p
INNER JOIN wp_2_term_relationships AS tr ON p.ID=tr.object_id
INNER JOIN wp_2_term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
INNER JOIN wp_2_terms AS t ON tt.term_id = t.term_id
WHERE 1=1
AND tt.taxonomy = 'myauthor'
AND p.post_type = 'post'
AND p.post_status = 'publish'
GROUP BY
N) AS x
INNER JOIN wp_2_posts p2
INNER JOIN wp_2_term_relationships AS tr2 ON p2.ID=tr2.object_id
INNER JOIN wp_2_term_taxonomy AS tt2 ON tr2.term_taxonomy_id = tt2.term_taxonomy_id
INNER JOIN wp_2_terms AS t2 ON tt2.term_id = t2.term_id
INNER JOIN wp_2_postmeta AS m2 ON m2.post_id = p2.ID
INNER JOIN wp_2_posts p3
INNER JOIN wp_2_term_relationships AS tr3 ON p3.ID=tr3.object_id
INNER JOIN wp_2_term_taxonomy AS tt3 ON tr3.term_taxonomy_id = tt3.term_taxonomy_id
INNER JOIN wp_2_terms AS t3 ON tt3.term_id = t3.term_id
INNER JOIN wp_2_postmeta AS m3 ON m3.post_id = p3.ID
WHERE 1=1
AND p3.post_type = 'author'
AND t3.name = x.N
AND m3.meta_key = 'firstname'
AND p2.post_type = 'author'
AND t2.name = x.N
AND m2.meta_key = 'lastname'
ORDER BY
C DESC,
L