无论META_KEY是否存在都获取帖子

时间:2021-04-04 作者:booota

我正在尝试使用$wpdb->get_results() 具体如下:

SELECT p.ID, p.post_content, p.post_title, p.post_excerpt, 
pm1.meta_value as meal_date, 
(case when pm2.meta_key is null then \'\' else pm2.meta_value end) as meal_plan,
t.name as meal_type 
FROM wp_posts AS p 
LEFT JOIN wp_term_relationships AS r ON (p.ID = r.object_id)
INNER JOIN wp_term_taxonomy AS x ON (r.term_taxonomy_id = x.term_taxonomy_id)
INNER JOIN wp_terms AS t ON (r.term_taxonomy_id = t.term_id)
INNER JOIN wp_postmeta As pm1 ON (p.ID = pm1.post_id)
INNER JOIN wp_postmeta As pm2 ON (p.ID = pm2.post_id)
WHERE p.post_type IN (\'knl_meals\') 
AND p.post_status = \'publish\'
AND x.taxonomy = \'knl_meal_types\'

AND pm1.meta_key = \'_knl_meal_date\'
AND pm2.meta_key = \'_knl_meal_regular\'

AND STR_TO_DATE(pm1.meta_value, \'%M %d, %Y\') BETWEEN CURRENT_DATE() AND DATE_ADD(DATE_ADD(CURRENT_DATE(), INTERVAL 1 MONTH), INTERVAL 5 DAY)
ORDER BY STR_TO_DATE(pm1.meta_value, \'%M %d, %Y\') ASC,t.term_id ASC, p.menu_order ASC, p.post_date DESC;
基本上,我希望Dine\\u计划是meta_value 对于meta_key = _knl_meal_regular 如果存在,则为post的空字符串/bool false etc type值,但post应包含在结果中。现在,如果一篇文章不存在meta\\u键,那么它将排除文章。

1 个回复
SO网友:booota

幸亏@Hobo\'s answer 这给了我将pm2条件移动到join语句的线索

SELECT p.ID, p.post_content, p.post_title, p.post_excerpt, pm1.meta_value as meal_date, pm2.meta_value as meal_plan, t.name as meal_type
FROM wp_posts AS p 
LEFT JOIN wp_term_relationships AS r ON (p.ID = r.object_id)
INNER JOIN wp_term_taxonomy AS x ON (r.term_taxonomy_id = x.term_taxonomy_id)
INNER JOIN wp_terms AS t ON (r.term_taxonomy_id = t.term_id)
INNER JOIN wp_postmeta As pm1 ON (p.ID = pm1.post_id)
LEFT JOIN wp_postmeta As pm2 ON (p.ID = pm2.post_id and pm2.meta_key=\'_knl_meal_regular\')
WHERE p.post_type IN (\'knl_meals\') 
AND p.post_status = \'publish\'
AND x.taxonomy = \'knl_meal_types\'

AND pm1.meta_key = \'_knl_meal_date\'
AND STR_TO_DATE(pm1.meta_value, \'%M %d, %Y\') BETWEEN CURRENT_DATE() AND DATE_ADD(DATE_ADD(CURRENT_DATE(), INTERVAL 1 MONTH), INTERVAL 5 DAY)
ORDER BY STR_TO_DATE(pm1.meta_value, \'%M %d, %Y\') ASC,t.term_id ASC, p.menu_order ASC, p.post_date DESC;

相关推荐

$wpdb的语法->在两列中搜索时准备

我有一个工作声明,用于在数据库中搜索单个列:$foods = $wpdb->get_results( $wpdb->prepare( "SELECT id, foodname, namevariations, calories, carbs, fat, protein, sodium FROM foodsTable WHERE namevariations like %s", "%$search_text%"), ARRAY_A );