我有一个查询来选择帖子(wp_posts table
),其中第一个表(wp_postmeta
)上有1个键/值对或另一个。从根本上说,这是有效的,但我需要按第一个键/对值(department_head
)排序,然后是第二个(staff_surname
)。
问题是,由于查询抓取结果的方式,没有department_head
键可用于对结果进行排序。我猜这是因为查询首先找到staff_surname
密钥?
再次猜测,但如果我的上述猜测是正确的那么这是因为,即使我加入表两次,MYSQL只是在wp_postmeta
表中抓取第一个实例staff_surname
条件得到满足。这是我需要找到的,所以我有正确的数据,以便能够订购结果。
完整查询 -
SELECT SQL_CALC_FOUND_ROWS wp_posts.*
FROM wp_posts
INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
INNER JOIN wp_postmeta AS mt1 ON (wp_posts.ID = mt1.post_id)
WHERE 1=1
AND (
wp_term_relationships.term_taxonomy_id IN (34)
)
AND wp_posts.post_type = 'people'
AND (
wp_posts.post_status = 'publish'
OR wp_posts.post_status = 'private'
)
AND (
(
wp_postmeta.meta_key = 'department_head'
AND CAST(wp_postmeta.meta_value AS CHAR) = 'private-client'
)
OR (
mt1.meta_key = 'staff_surname'
AND CAST(mt1.meta_value AS CHAR) != ''
)
)
GROUP BY wp_posts.ID
ORDER BY mt1.meta_value ASC
LIMIT 0, 10
查询结果示例 -
ID name meta_id post_id meta_key meta_value meta_id post_id meta_key meta_value
1 Test1 10 1 random_key random_value 11 1 staff_surname Smith
2 Test1 20 2 random_key random_value 21 2 staff_surname Jones
3 Test1 30 3 random_key random_value 31 3 staff_surname Harris
如果琼斯是部门主管,我需要的例子 -
ID name meta_id post_id meta_key meta_value meta_id post_id meta_key meta_value
1 Test1 10 1 11 1 staff_surname Smith
2 Test1 22 2 department_head private-client 21 2 staff_surname Jones
3 Test1 30 3 31 3 staff_surname Harris
在绝大多数情况下,'department_head'键不存在,这就是其他resute上的键/值为空的原因。
有没有办法实现我需要的订购结果?
注意:我在这里发布此内容而不是Wordpress网站的原因是因为这是一个自定义查询,而不是WP生成的,所以它可能超出了大多数WP的范围专家。
答案 0 :(得分:1)
我不确定,但我会尝试使用一些LEFT JOINS来处理这个问题并将条件移到JOINS以使查询更有效。
与此类似的东西可能有用......
SELECT p.*
FROM wp_posts p
INNER JOIN wp_term_relationships r ON
(p.ID=r.object_id AND r.term_taxonomy_id=34)
LEFT JOIN wp_postmeta m1 ON
(p.ID=m1.post_id AND m1.meta_key='department_head' AND CAST(m1.meta_value AS CHAR)='private-client')
LEFT JOIN wp_postmeta m2 ON
(p.ID=m2.post_id AND m2.meta_key = 'staff_surname' AND CAST(m2.meta_value AS CHAR) != '')
WHERE
p.post_type = 'people'
AND
(p.post_status = 'publish' OR p.post_status = 'private')
GROUP BY p.ID
ORDER BY m1.meta_value DESC, m2.meta_value DESC
LIMIT 0, 10