道歉,如果这是相当基本的,我有点超出我的深度,可以使用一些指导来填补一些空白。
这是情况...... 我正在查询WordPress数据库,以返回与元键/值条件相关的一组特定条件匹配的帖子子集(具体来说,'dates'的键是否包含与下一个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 *键和值月的帖子,其中< em>月是当月。 我已经扩展了代码以允许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'
但是,添加此内容会返回零结果。我已经测试了查询一个的条件(匹配当月的第一天,或匹配月),我可以返回一个或另一个没问题。我很确定问题是我在同一个字符串中查询同一个变量两次,不考虑排序或区别。重建此查询以恢复的最佳方法是什么:
这是最后的加价。问题只是我的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')) )";
答案 0 :(得分: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' )
)
)