簡體   English   中英

如何減少為此工作所需的 SQL 查詢的數量?

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

所以.. 我懂一點編程,但我的技能有限。 今天,我正在嘗試進行一個簡單的查詢,以讓在我選擇的日期之間在我目前工作的醫院工作的健康人員。

我想要 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。

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

您可以使用案例表達式和條件邏輯:

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 (即不是由用戶提供)或設置(即由用戶提供):參數:starting_date_after:starting_date_before用於過濾表列starting_date ,而:ending_date_after:ending_date_before適用於ending_date

請注意,您應該使用參數化查詢(如上所示)而不是在查詢字符串中連接變量,以使您的代碼更高效,更重要的是,防止 SQL 注入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM