wpdb query - 即使缺少值,如何显示结果?

时间:2016-03-09 15:42:07

标签: php mysql wordpress wpdb

我已经读过,如果'$ wpdb-> get_results'查询中缺少数据,那么结果将完全为空。

我的查询如下:

var map = new ol.Map({
        target: 'map',
        layers: [
            new ol.layer.Vector({
                source: new ol.source.Vector({
                    url: 'example.osm',
                    format: new ol.format.OSMXML(),

然后

$results = $wpdb->get_results("

SELECT 
( SELECT guid FROM ch_posts WHERE id = m.meta_value ) AS thumbnail, ID, post_title, post_name, SUBSTR(post_content, 20) AS content, post_date, t.name AS category

FROM ch_posts, ch_postmeta m

JOIN ch_term_relationships tr
JOIN ch_terms t ON t.term_id = tr.term_taxonomy_id 
JOIN ch_term_taxonomy tx ON tr.term_taxonomy_id = tx.term_taxonomy_id

WHERE post_status = 'publish'
AND post_author = $user_ID
AND post_type = 'product'
AND ch_posts.ID = m.post_id
AND m.meta_key =  '_thumbnail_id'
AND tr.object_id = ch_posts.ID
AND tx.taxonomy = 'product_cat'
");

由于我的帖子缺少“缩略图”记录,因此不会显示整个结果集。是否可以修改我的查询以显示找到的结果,并忽略那些缺失的结果?或者用其他东西替换缺失的值?

我尝试过使用CASE,但无济于事。

欢迎任何帮助

1 个答案:

答案 0 :(得分:0)

1,您的查询未满。显示整个查询。 2,你正在以错误的方式获取缩略图网址。 3,对于获取缩略图的表,连接不应该是内部的。使用缩略图获取20个最后帖子的示例(NULL为无)

SELECT `posts`.`ID` AS `ID`, `posts`.`post_title` AS `title`, `posts`.`post_name` AS `slug`, `posts`.`post_content` AS `content`, `posts`.`post_excerpt` AS `excerpt`, `thumb_link` FROM `wp_posts` AS `posts`
LEFT JOIN (select `thumb`.`post_id` AS `object_id`, `thumbs_link`.`meta_value` AS `thumb_link` from `wp_postmeta` AS `thumb` 
LEFT JOIN`wp_postmeta` AS thumbs_link ON (`thumbs_link`.`post_id` = `thumb`.`meta_value`) 
AND `thumbs_link`.meta_key = "_wp_attached_file" WHERE `thumb`.`meta_key` = '_thumbnail_id' 
GROUP BY `thumb`.`post_id` ) AS `thumb`  ON `thumb`.`object_id` = `posts`.`ID`
WHERE `posts`.`post_status` = 'publish'
ORDER BY `posts`.`ID` DESC
LIMIT 20