Mysql

帶參數的視圖,可以嗎?

  • May 19, 2019

我在一個 PHP 應用程序中工作,一些“複雜”的查詢開始出現在程式碼中。由於復雜性,我無法使用任何 ORM,並且我擁有的唯一資源是我不喜歡的普通 SQL 和 PHP MySQL 本機函式。

這裡沒有更多是我想轉換為視圖的查詢之一:

SELECT
 COUNT(*) AS 'rec',
 CONCAT(
     IF(agreement_list.ActiveFlag, '', 'Agreement is Inactive.'),
     IF(agreement_type.ActiveFlag, '', 'Agreement Type is Inactive.'),
     IF(distributor.ActiveFlag, '', 'License Distributor is InActive.'),
     IF(agreement_distributor.ActiveFlag, '', 'Agreement Distributor is InActive.'),
     IF(customer.ActiveFlag, '', 'Customer is Inactive.'),
     IF(cf_program_level.ActiveFlag, '', 'Program Level is Inactive.')
 ) AS errormessage,
 IF((agreement_list.ActiveFlag + agreement_type.ActiveFlag + distributor.ActiveFlag + agreement_distributor.ActiveFlag + customer.ActiveFlag + cf_program_level.ActiveFlag) < 6, 1, 0 ) AS error
FROM
 license
 JOIN agreement_list ON (agreement_list.AgreementTypeID = license.AgreementTypeID AND agreement_list.CustomerSiteID = license.CustomerSiteID AND agreement_list.Source = license.Source)
 JOIN customer ON (customer.id = license.CustomerSiteID AND license.source = customer.Source)
 JOIN distributor ON (distributor.DistributorID = license.DistributorID AND license.source = distributor.Source)
 JOIN distributor AS agreement_distributor ON (agreement_distributor.DistributorID = agreement_list.DistributorID AND agreement_list.source = agreement_distributor.Source)
 JOIN agreement_type ON (agreement_type.AgreementTypeID = license.AgreementTypeID AND license.source = agreement_type.Source)
 JOIN cf_program_level ON (cf_program_level.CFProgramLevelID = '{$CFProgramLevelID}' AND license.source = cf_program_level.Source)
WHERE
 license.AgreementTypeID = '{$AgreementTypeID}'
 AND license.CustomerSiteID = '{$CustomerSiteID}'
 AND license.Source = '{$Source}'

$CFProgramLevelID, $AgreementTypeID, $CustomerSiteID, $Source是來自 PHP 的參數,這是我唯一的問題。如果可能,如何將參數傳遞給視圖?

我目前正在使用 MySQL 5.6。

看起來很簡單。建構VIEW沒有最後 5 行的。然後在使用時使用這 5 行,VIEW就好像它是TABLE.

如果那些JOINs不是“many:one”,你會得到一個膨脹的COUNT(*).

更好的是,您可以通過創建一個函式以從會話變數中獲取您的值,以一種簡單的方式將參數傳遞給您的視圖。

有關該技術,請參見 www.stackoverflow.com/questions/14511760。這是我的創建功能的副本,您可能希望模仿。

DELIMITER //

CREATE FUNCTION fn_getcase_id()    
RETURNS MEDIUMINT(11)
DETERMINISTIC NO SQL
BEGIN
# see stackoverflow.com/questions/14511760 and read ALL the info TWICE or MORE.  wh 04/13/2017
   RETURN @sv_case_id;
END//

DELIMITER ;

您將需要創建 4 個類似的 FN(每個變數一個)。

引用自:https://dba.stackexchange.com/questions/185474