【问题标题】:How can I reduce the number of SQL queries I need for this to work?如何减少为此工作所需的 SQL 查询数量?
【发布时间】:2020-11-29 00:43:48
【问题描述】:

所以.. 我懂一点编程,但我的技能有限。今天,我试图进行一个简单的查询,以便在我选择的日期之间找到在我目前工作的医院工作的健康人员。

我想要 4 个输入日期,例如

它是西班牙语,所以这里是翻译:

日期输入是“过滤器”

Started working >= to this date
Started working <= to this date
Quit the job >= to this date
Quit the job <= to this date

而2选输入的是个人拥有的职称和专业程度。 (我需要两者都可以为空的选项)

所以我可以解决这个问题,为每个可能的情况创建一个 SQL 查询,如下所示:

    if ($titulo == '0' && $especialidad == '0' && $date1!=null && $date2==null && 
$bdesde==null && $bhasta==null){     

$sql_query= "select * from personal where starting_date >= '$date1'" }
    
elseif ( ... and so on  

数据库是 MySQL。

但我想知道是否有办法用更少的代码做我想做的事。

【问题讨论】:

    标签: php html mysql sql where-clause


    【解决方案1】:

    您可以使用案例表达式和条件逻辑:

    select * 
    from personal 
    where 
        (:starting_date_after      is null or starting_date >= :starting_date_after)
        and (:starting_date_before is null or starting_date <= :starting_date_before)
        and (:ending_date_after    is null or ending_date   >= :ending_date_after)
        and (:ending_date_before   is null or ending_date   <= :ending_date_before)
    

    这假设你的查询接受4个参数,可能是null(即非用户提供)或set(即用户提供):参数:starting_date_after:starting_date_before用于过滤表列starting_date,而:ending_date_after:ending_date_before 适用于ending_date

    请注意,您应该使用参数化查询(如上所示)而不是在查询字符串中连接变量,以使您的代码更高效,更重要的是,防止 SQL 注入。

    【讨论】:

    • 我试过了,但它不起作用。我不知道我是否错了,但在这种情况下,如果starting_date_after 为空,那么查询将带来个人的所有值。我证明并且有效的唯一解决方案是使用 IF 语句获取所有可能的组合。但它的4!可能性 (24) 不计算其他 2 个过滤器(职称和专业程度)
    • @nap_-: 如果starting_date_after 为null,那么查询会从personal 中获取所有值。:不,它也取决于其他参数。只有当所有 4 个参数都是null 时,查询才会返回所有行(这似乎合乎逻辑)。
    • 是的,我的错。问题是starting_date_after 不是null,而是一个空字符串。我不知道是否是最好的解决方案,但我在 where ´´(starting_date_after = ' ' or starting_date >= starting_date_after) ´´
    • @nap_-:你可以处理空字符串,比如(:starting_date_after is null or :starting_date_after = '' or starting_date &gt;= :starting_date_after),等等。
    • 是的。我就是这么做的。感谢您的回答。我还是个编程菜鸟T_T
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    相关资源
    最近更新 更多