【问题标题】:SQL left join not giving me null entriesSQL左连接不给我空条目
【发布时间】:2014-09-12 19:42:34
【问题描述】:

我正在为 wordpress 制作 rss 提要,如果文章设置了促销日期,则要求应按促销日期排序,否则使用 post_date 使用以下 SQL。

SELECT $wpdb->posts.* from $wpdb->posts 
LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) 
LEFT JOIN $wpdb->terms ON ($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id) 
LEFT JOIN $wpdb->postmeta as m2 on ($wpdb->posts.ID=m2.post_id and m2.meta_key='promotion_date') 
where now()>(CASE WHEN m2.meta_value IS NOT NULL 
    then cast(m2.meta_value as DATETIME) 
    ELSE $wpdb->posts.post_date END) 
and $wpdb->posts.post_status='publish' 
and $wpdb->posts.post_type='article' 
and $wpdb->terms.slug = $slug 
and $wpdb->term_taxonomy.taxonomy = 'article_$taxonomy' 
order by CASE WHEN m2.meta_value IS NOT NULL 
      then cast(m2.meta_value as DATETIME) 
      ELSE $wpdb->posts.post_date 
END DESC limit 100;

问题是左连接似乎不会返回没有促销日期的条目。当没有匹配项时,左连接通常会从第一个表中选择所有包含空条目的列。为什么在这种情况下没有发生?

【问题讨论】:

    标签: mysql wordpress


    【解决方案1】:

    您在 $slug 的“terms”和 WHERE 子句中的“term_taxonomy”查询中有两个“AND”条件,因此将 LEFT-JOIN 转换为 INNER-JOIN。我已将它们移至 LEFT JOIN 组件。否则你应该很好(另外,我只是为表格应用了别名,而不是为了可读性而使用手写)

    SELECT 
          p.* 
       from 
          $wpdb->posts p
             LEFT JOIN $wpdb->term_relationships tr
                ON p.ID = tr.object_id
                LEFT JOIN $wpdb->term_taxonomy tt
                   ON tr.term_taxonomy_id = tt.term_taxonomy_id
                  and tt.taxonomy = 'article_$taxonomy' 
                   LEFT JOIN $wpdb->terms t 
                      ON tt.term_id = t.term_id
                     and t.slug = $slug 
             LEFT JOIN $wpdb->postmeta as m2 
                on p.ID = m2.post_id 
                and m2.meta_key = 'promotion_date'
       where 
              now() > ( CASE WHEN m2.meta_value IS NOT NULL 
                         then cast(m2.meta_value as DATETIME) 
                         ELSE p.post_date END )
          and p.post_status = 'publish' 
          and p.post_type = 'article' 
       order by 
          CASE WHEN m2.meta_value IS NOT NULL 
             then cast(m2.meta_value as DATETIME) 
             ELSE p.post_date END DESC 
       limit 100;
    

    为了查询性能,我建议您在 (post_status, post_type, post_date) 的 post 表上建立一个索引

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-13
      • 2011-12-11
      • 1970-01-01
      • 2016-05-23
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多