MySQl 基于过滤值的查询

问题描述 投票:0回答:2

我有一个包含一些字段(语言、日期、日期、状态)的表单。有一个提交按钮。我想根据这些字段上填写的值获取数据。我的查询忽略了不是的字段已满。我该如何编写查询。

Select * from tbldep where (language='$language') AND ( Date between '$Datefrom' AND '$Dateto')AND (status='$status')

我的查询忽略未填充的值。假设用户没有在 DateFrom 字段中填写日期值,那么查询应该获取所有小于 DateTo 值的记录。

mysql sql where-clause
2个回答
0
投票

IFNULL。如果没有日期,将 null 替换为默认值,这将获取您想要的数据。

Select * 
  from tbldep 
  where (language='$language') 
    AND ( Date between IFNULL('$Datefrom', '1900/01/01') AND '$Dateto')
    AND (status='$status')

0
投票

你可以使用布尔逻辑——尽管表达起来有点冗长:

select * 
from tbldep 
where (:lang    is null or language = :lang) 
  and (:dt_from is null or date    >= :dt_from)
  and (:dt_to   is null or date    <= :dt_to)
  and (:stat    is null or status   = :stat)

请注意,这使用绑定参数(带有

:
前缀)而不是字符串连接来构建查询(这是不可靠和不安全的)。

© www.soinside.com 2019 - 2024. All rights reserved.