[英]Condition if else inside mysql request
我想在SQL請求中插入if / else條件。 我該怎么做呢? 我已經在下面嘗試過了,但是沒有用:
$QpageManagerGeneralCondition = $OSCOM_PDO->prepare('
select pmd.pages_html_text,
pm.page_general_condition
from :table_pages_manager pm,
:table_pages_manager_description pmd
where
if (pm.customers_group_id = :customers_group_id) else (pm.customers_group_id = 99)
and pm.page_general_condition = 1
and pmd.language_id = :language_id
and pmd.pages_id = pm.pages_id
limit 1
');
$QpageManagerGeneralCondition->bindInt(':language_id',(int)$_SESSION['languages_id'] );
$QpageManagerGeneralCondition->bindInt(':customers_group_id',$OSCOM_Customer->getCustomersGroupID() );
$QpageManagerGeneralCondition->execute();
$QpageManagerGeneralCondition->value('pages_html_text');
我認為您正在尋找CASE語句。 例如,您可以使用case語句為“ is_a_senior”列使用不同的值。 在此示例中,如果year ='SR',則列'is_a_senior'的值為yes。
SELECT player_name,
year,
CASE WHEN year = 'SR' THEN 'yes'
ELSE 'no' END AS is_a_senior
FROM benn.college_football_players
參見https://sqlschool.modeanalytics.com/intermediate/case/
-
對於您的特定示例,看起來您實際上可能實際上不需要條件,並且向查詢添加默認值就足夠了。
ISNULL(pm.customers_group_id, 99) AS pm.customers_group_id
如果您不僅需要ISNULL檢查,還可以查看COALESCE關鍵字。 COALESCE是一個功能非常強大的命令,如果null檢查發現為null,則可以有條件地將子查詢添加到查詢中。
我看到您正在使用PHP / PDO來查詢數據庫,您可以只使用php中的條件表達式(而不是SQL中的條件表達式)並根據if的哪一側執行查詢來編輯查詢。 這可能更快。
條件表達式也是一個選項。 為此提到這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.