简体   繁体   English

如何减少为此工作所需的 SQL 查询的数量?

[英]How can I reduce the number of SQL queries I need for this to work?

So.. I know a little bit of programming but my skills are limited.所以.. 我懂一点编程,但我的技能有限。 Today I'm trying to make a simple query to get the health personal working at the hospital I currently work in between the dates I choose.今天,我正在尝试进行一个简单的查询,以让在我选择的日期之间在我目前工作的医院工作的健康人员。

I want to have 4 input dates like我想要 4 个输入日期,例如

这个

Its in spanish so here is the traduction:它是西班牙语,所以这里是翻译:

The date inputs are "filters"日期输入是“过滤器”

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

And the 2 selects inputs are the title and specialization degree that personal have.而2选输入的是个人拥有的职称和专业程度。 (I need the option that both can be null) (我需要两者都可以为空的选项)

So I can work around this making an SQL query for every possible case like this:所以我可以解决这个问题,为每个可能的情况做一个 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  

The database is MySQL.数据库为 MySQL。

But I was wondering if there is a way to do what I want with less code.但我想知道是否有办法用更少的代码做我想做的事。

You could use case expressions and conditional logic:您可以使用案例表达式和条件逻辑:

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)

This assumes that your query accepts 4 parameters, which may be null (ie not provided by the user) or set (ie given by the user): parameters :starting_date_after and :starting_date_before are meant to filter table column starting_date , while :ending_date_after and :ending_date_before apply to ending_date .这假设您的查询接受 4 个参数,可能是null (即不是由用户提供)或设置(即由用户提供):参数:starting_date_after:starting_date_before用于过滤表列starting_date ,而:ending_date_after:ending_date_before适用于ending_date

Note that you should be using parameterized queries (as shown above) rather than concatenating variables in the query string, to make your code more efficient, and, more importantly, to prevent SQL injection.请注意,您应该使用参数化查询(如上所示)而不是在查询字符串中连接变量,以使您的代码更高效,更重要的是,防止 SQL 注入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM