Can Parameters Be Incorporated into MySQL Views?
The initial query attempts to create a view with a parameter, but MySQL prohibits this. The workaround presented involves creating a function to retrieve the parameter value, then incorporating it into the view's definition. However, this approach is deemed unsatisfactory due to its complexity and lack of elegance.
The main goal is to create a view where parameters can be utilized directly, facilitating data grouping and filtering. Consider the MergedDenialsViewHelper and MergedDenials views. To display denials for specific users and features within a defined time frame, a parameter is employed:
SET @DenialMergingTime := 5; SELECT GroupTime, FeatureId, UserHostId, MultiplicitySum FROM MergedDenials WHERE UserHostId IN (1, 2) AND FeatureId IN (3, 4);
This method, while effective, is problematic due to its convoluted nature. An alternative approach exists: creating a function to return the desired parameter value.
create function p1() returns INTEGER DETERMINISTIC NO SQL return @p1;
Subsequently, a view can be created with the function incorporated:
create view h_parm as select * from sw_hardware_big where unit_id = p1() ;
With this view in place, parameters can be directly utilized:
select s.* from (select @p1:=12 p) parm , h_parm s;
This solution eliminates the need for the previous workaround, simplifying the overall process and enhancing the readability of the code.
The above is the detailed content of Can MySQL Views Accept Parameters for Dynamic Data Filtering?. For more information, please follow other related articles on the PHP Chinese website!