doucanrui1735 2013-04-17 13:40
浏览 35
已采纳

SQL字符串为我提供了一个类别的所有帖子,但没有没有

I'm running a Wordpress site, and I'm making a widget that gives me all posts that are the most read in the last 8 days.

When I run this SQL string I get all the posts with a category, but when a post isn't in a category, I don't get it.

How do I get all the posts that ARE in a category, AND all the posts that AREN'T in a category?

My sql string

$sql ="SELECT wp_posts.post_date, wp_posts.post_title, wp_posts.post_name, wp_posts.post_content, wp_terms.name, wp_terms.slug, wp_postmeta.meta_value FROM wp_posts
        INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
        INNER JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
        INNER JOIN wp_terms ON (wp_term_taxonomy.term_id = wp_terms.term_id)
        INNER JOIN wp_postmeta ON (wp_postmeta.post_id = wp_posts.ID)
        WHERE (wp_term_taxonomy.taxonomy = 'category'
           AND wp_postmeta.meta_key = 'readCount'
           AND wp_posts.post_type = 'post'
           AND DATE(wp_posts.post_date) >= '$eight_days_ago'
           AND wp_posts.post_status = 'publish')
           GROUP BY wp_posts.ID
           ORDER BY wp_postmeta.meta_value DESC
           LIMIT 5";
  • 写回答

2条回答 默认 最新

  • dslk6326846 2013-04-17 14:01
    关注

    I think this will work. You need to change the joins to left outer joins and then check for NULL in the where clause:

    SELECT wp_posts.post_date, wp_posts.post_title, wp_posts.post_name, wp_posts.post_content, wp_terms.name, wp_terms.slug, wp_postmeta.meta_value FROM wp_posts
            LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
            LEFT JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
            LEFT JOIN wp_terms ON (wp_term_taxonomy.term_id = wp_terms.term_id)
            LEFT JOIN wp_postmeta ON (wp_postmeta.post_id = wp_posts.ID)
            WHERE ((wp_term_taxonomy.taxonomy = 'category') or (wp_term_taxonomy.taxonomy is NULL))
               AND wp_postmeta.meta_key = 'readCount'
               AND wp_posts.post_type = 'post'
               AND DATE(wp_posts.post_date) >= '$eight_days_ago'
               AND wp_posts.post_status = 'publish')
               GROUP BY wp_posts.ID
               ORDER BY wp_postmeta.meta_value DESC
               LIMIT 5
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊