我正在尝试使用$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键,那么它将排除文章。
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;