在mysql语句中使用if语句

时间:2011-04-14 02:00:08

标签: php mysql sql

我正在使用通用wordpress sql语句来获取帖子标题。我想用一个seo插件中的allmeta值的postmeta值替换帖子标题是帖子中存在的一体化seo标题。

如何在sql命令中使用此if语句?

没有all in one if语句的现有代码。

//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");    

菲尔的回答后现在出现错误的新功能

$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");    

1 个答案:

答案 0 :(得分:1)

我在LEFT JOIN表格上使用COALESCE()post_meta。例如(注意,仅通用查询,与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'