Using if statements in mysql statements
I'm using a generic wordpress sql statement to grab the post titles. I want to replace the post titles with a postmeta value of the all in one seo plugin is an all in one seo title exists for the post.
How do I use this if statement in the sql command?
Existing code without the all in one if statement.
//Limit to last 30 days, 1,000 items
$rows = $wpdb->get_results("SELECT $wpdb->posts.ID, $wpdb->posts.post_date_gmt, $wpdb->posts.post_title
FROM $wpdb->posts, $wpdb->postmeta
WHERE $wpdb->posts.post_status='publish'
AND (DATEDIFF(CURDATE(), post_date_gmt)<=30)
$includeMe
ORDER BY $wpdb->posts.post_date_gmt DESC
LIMIT 0, 1000");
New Function That's G开发者_开发问答etting an Error Now after Phil's Answer
$rows = $wpdb->get_results("SELECT COALESCE($wpdb->postmeta.meta_value, $wpdb->posts.post_title) AS post_title, $wpdb->posts.post_date_gmt, $wpdb->posts.ID
FROM $wpdb->posts
LEFT JOIN $wpdb->post_meta
ON $wpdb->posts.ID = $wpdb->postmeta.post_id
AND $wpdb->postmeta.meta_key = '_aioseop_title'
WHERE $wpdb->posts.post_status='publish'
AND (DATEDIFF(CURDATE(), post_date_gmt)<=30)
$includeMe
ORDER BY $wpdb->posts.post_date_gmt DESC
LIMIT 0, 1000");
I'd use COALESCE()
with a LEFT JOIN
on the post_meta
table. For example (note, generic query only, not directly related to Wordpress)
SELECT COALESCE(post_meta.value, posts.title) AS title
FROM posts
LEFT JOIN post_meta
ON posts.id = post_meta.post_id
AND post_meta.key = 'some_meta_key'
精彩评论