dongyun51582 2019-05-12 03:21
浏览 453

MySQL如果值为null则不搜索

I have the following query:

SELECT nfc_film.title, nfc_film.film_id, nfc_film.description, nfc_film.release_year, nfc_film.rating, nfc_film.last_update, nfc_category.name 
  FROM nfc_film
  JOIN nfc_film_category
    ON nfc_film.film_id = nfc_film_category.film_id
  JOIN nfc_category
    ON nfc_film_category.category_id = nfc_film_category.category_id
 WHERE
       nfc_film.title LIKE :searchterm
   AND
       nfc_category.name = :category
 LIMIT 10
OFFSET :page

I'm aware of the IFNULL() function. But say if :category was either empty or null, how would i just make the query as if that condition wasn't in there.

So like If :category is null then don't search in nfc_category.name

  • 写回答

1条回答 默认 最新

  • doufangzhang4454 2019-05-12 03:30
    关注

    You can just change your WHERE conditions to include empty/null tests for category. If it is empty or NULL, the result of the nfc_category.name = :category will be irrelevant (and should be optimised away). Note the need for parentheses to avoid operator precedence issues.

    (:category = '' OR :category IS NULL OR nfc_category.name = :category)
    

    Dependent on your PDO::ATTR_EMULATE_PREPARES setting, you may need to use another parameter name e.g. :category0, :category1 for the second and third usage of the parameter.

    评论

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?