2

我有一堆带有元键的自定义帖子类型页脚元素footer_element_meta_alignment。现在,我正在尝试获取三个最新的帖子,它们meta_values1和。因此,每个值都有一个帖子。23

如何使用单个 SQL 查询来实现这一点?

到目前为止,这是我的 SQL 查询:

"SELECT wposts.*, meta1.meta_value
FROM $wpdb->posts wposts, $wpdb->postmeta meta1
WHERE 1=1
AND wposts.post_type = 'footer_element'
AND wposts.post_status = 'publish'
AND wposts.ID = meta1.post_id
AND meta1.meta_key = 'footer_element_meta_alignment'
AND (meta1.meta_value = 1 OR meta1.meta_value = 2 OR meta1.meta_value = 3)
ORDER BY meta1.meta_value ASC";

然而,这会获取具有给定元值的所有元素,而不仅仅是最新的元素。

答案
回答了我自己的问题。

4

2 回答 2

0

固定(我希望)。

 SELECT wposts.* FROM $wpdb->posts wposts WHERE
 wposts.post_type = 'footer_element'
 AND wposts.post_status = 'publish'
 AND wposts.ID IN 
 (SELECT max(meta1.post_id) FROM $wpdb->postmeta meta1
 WHERE meta1.meta_value = 1 OR meta1.meta_value = 2 OR meta1.meta_value = 3
 GROUP BY meta1.meta_value)
于 2013-03-04T10:51:22.040 回答
0

经过几个小时的努力,我找到了解决方案。

SQL

"SELECT *
 FROM (  SELECT p.*, m.meta_value AS meta
         FROM $wpdb->posts AS p
         LEFT JOIN $wpdb->postmeta AS m
         ON p.ID = m.post_id
         WHERE m.meta_key = 'footer_element_meta_alignment'
         AND p.post_status = 'publish'
         ORDER BY m.meta_value ASC, p.post_date DESC) AS h
 GROUP BY meta";
于 2013-03-04T13:32:45.100 回答