如果Select in SQL IN语句返回NULL,则选择ALL

时间:2016-03-09 18:55:52

标签: php mysql sql select prepared-statement

我试图缩短代码并加快速度。 但是,我在这个声明中苦苦挣扎。 如果未设置值page_category,我希望它返回所有新闻。

page_category在数据库中设置为1,2,3,4,每篇新闻文章都有如下所示的1个类别。

页面类别

Page Category

新闻类别

news

我想获取每个类别为page_category的新闻文章。

这是我的陈述,只要设置page_category,它就可以正常工作。

"AND n.news_category IN (SELECT page_category FROM pages WHERE page_name = :pagename AND page_deleted IS NULL)";

如何重写此内容,以便n.news_category如果返回NULL则不计算?

这是我目前的全部陈述:

 $sql = "SELECT n.news_title, n.news_content, n.news_published_dt "
      . "FROM news n "
      . "LEFT JOIN languages l "
      . "ON n.news_lang = l.language_id "
      . "WHERE ((l.language_val = :language) OR (n.news_lang_all IS NOT NULL)) "
      . "AND n.news_deleted IS NULL "
      . "AND n.news_published = 1 "
      . "AND n.news_category IN (SELECT page_category FROM pages WHERE page_name = :pagename AND page_deleted IS NULL)";

1 个答案:

答案 0 :(得分:0)

假设page_category具有NULL值并且您想要所有行,那么请改用exists

EXISTS (SELECT 1
        FROM pages p
        WHERE p.page_name = :pagename AND p.page_deleted IS NULL AND
              (p.page_category is null or p.page_cateogry = n.news_category)
       )