0

抱歉,如果这是相当基本的,我有点超出我的深度,可以使用一些指导来填补一些空白。

这是情况......我正在查询 WordPress 数据库以返回与一组与元键/值条件相关的特定条件匹配的帖子子集(具体来说,“日期”的键是否包含与下一个匹配的值X 天)。这工作正常 - 代码当前是:

$request  = "SELECT DISTINCT ID FROM $wpdb->posts, $wpdb->postmeta";
$request .= " WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id";
$request .= " AND post_status='publish' AND post_type='days'";
$request .= " AND $wpdb->postmeta.meta_key = 'dates' AND $wpdb->postmeta.meta_value >= '$startDate' AND $wpdb->postmeta.meta_value <= '$endDate' AND $wpdb->postmeta.meta_value != '$today'";

现在,我想介绍另一种情况,并返回任何具有 *_dayType* 键和month值的帖子,其中月份是当前月份。我已经扩展了代码以允许 OR 规则也返回与当月第一天匹配的帖子。扩展代码如下所示:

$request  = "SELECT DISTINCT ID FROM $wpdb->posts, $wpdb->postmeta";
$request .= " WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id";
$request .= " AND post_status='publish' AND post_type='days'";
$request .= " AND ";
$request .= " (($wpdb->postmeta.meta_key = 'dates' AND $wpdb->postmeta.meta_value >= '$startDate' AND $wpdb->postmeta.meta_value <= '$endDate' AND $wpdb->postmeta.meta_value != '$today')";
$request .= " OR ";
$request .= " ($wpdb->postmeta.meta_key = 'dates' AND $wpdb->postmeta.meta_value = '$firstDayOfMonth' ))";

现在我遇到了一个问题。我想通过再次查询 meta_key 变量来扩展返回新月帖子的条件。例如,

$wpdb->postmeta.meta_key = '_dayType' AND $wpdb->postmeta.meta_value = 'month'

但是,添加它会返回零结果。我已经测试了只查询一个条件(匹配一个月的第一天,或者匹配一个月),我可以毫无问题地返回一个或另一个。我很确定问题是我在同一个字符串中查询同一个变量两次,没有考虑排序或区分。重建此查询以恢复的最佳方法是什么:

  • 与接下来 X 天匹配的帖子或
  • “月”的帖子

这是最后的标记。问题只是我的 AND 嵌套语法吗?

$request  = "SELECT DISTINCT ID FROM $wpdb->posts, $wpdb->postmeta";
$request .= " WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id";
$request .= " AND post_status='publish' AND post_type='days'";
$request .= " AND ";
$request .= " (($wpdb->postmeta.meta_key = 'dates' AND $wpdb->postmeta.meta_value >= '$startDate' AND $wpdb->postmeta.meta_value <= '$endDate' AND $wpdb->postmeta.meta_value != '$today')";
$request .= " OR ";
$request .= " (($wpdb->postmeta.meta_key = 'dates' AND $wpdb->postmeta.meta_value = '$firstDayOfMonth') AND ($wpdb->postmeta.meta_key = '_daytype' AND $wpdb->postmeta.meta_value = 'month')) )";
4

1 回答 1

0

解决; 需要通过 OR 而不是 AND 查询多个键,因为变量现在不能同时具有两个值,可以吗?

SELECT DISTINCT ID FROM wp_posts, wp_postmeta 
WHERE (
 wp_posts.ID = wp_postmeta.post_id
 AND post_status = 'publish'
 AND post_type = 'days'
 AND (
  wp_postmeta.meta_key = 'dates' 
  AND wp_postmeta.meta_value >= '$startDate' 
  AND wp_postmeta.meta_value <= '$endDate' 
  AND wp_postmeta.meta_value != '$today'
 )
)
UNION
SELECT DISTINCT ID FROM wp_posts, wp_postmeta 
WHERE (
 wp_posts.ID = wp_postmeta.post_id
 AND post_status = 'publish'
 AND post_type = 'days'
 AND (
 (wp_postmeta.meta_key = '_dayType' AND wp_postmeta.meta_key = 'month')
 OR
 (wp_postmeta.meta_key = 'dates' AND wp_postmeta.meta_value = '$firstDayOfMonth' )
 )
)
于 2012-12-22T15:55:36.017 回答