我有这样的看法:
CREATE VIEW MyView AS
SELECT Column FROM Table WHERE Value = 2;
我想使其更通用,这意味着将2更改为变量。我尝试了这个:
CREATE VIEW MyView AS
SELECT Column FROM Table WHERE Value = @MyVariable;
但是MySQL不允许这样做。
我发现了一个丑陋的解决方法:
CREATE FUNCTION GetMyVariable() RETURNS INTEGER DETERMINISTIC NO SQL
BEGIN RETURN @MyVariable; END|
然后视图是:
CREATE VIEW MyView AS
SELECT Column FROM Table WHERE Value = GetMyVariable();
但是它看起来确实很糟糕,用法也很糟糕-我必须在每次使用视图之前设置@MyVariable。
有没有一种解决方案,我可以这样使用:
SELECT Column FROM MyView(2) WHERE (...)
具体情况如下:我有一个表,存储有关被拒绝的请求的信息:
CREATE TABLE Denial
(
Id INTEGER UNSIGNED AUTO_INCREMENT,
PRIMARY KEY(Id),
DateTime DATETIME NOT NULL,
FeatureId MEDIUMINT UNSIGNED NOT NULL,
FOREIGN KEY (FeatureId)
REFERENCES Feature (Id)
ON UPDATE CASCADE ON DELETE RESTRICT,
UserHostId MEDIUMINT UNSIGNED NOT NULL,
FOREIGN KEY (UserHostId)
REFERENCES UserHost (Id)
ON UPDATE CASCADE ON DELETE RESTRICT,
Multiplicity MEDIUMINT UNSIGNED NOT NULL DEFAULT 1,
UNIQUE INDEX DenialIndex (FeatureId, DateTime, UserHostId)
) ENGINE = InnoDB;
多重性是同一秒记录的多个相同请求。我想显示一个拒绝列表,但是有时候,当应用程序被拒绝时,它会重试几次以确保。因此通常,当同一用户在几秒钟内对同一功能拒绝3次时,实际上是一次拒绝。如果我们还有一个资源可以满足此请求,则不会发生接下来的两次拒绝。因此,我们希望将拒绝项分组到报告中,以便用户指定拒绝项的分组时间。例如,如果我们在时间戳记:(特征1中的用户1)的拒绝时间为1,2,24,26,27,45,并且用户希望将彼此之间相距不超过4秒的拒绝分组,则他应该得到如下信息: 1(x2),24(x3),45(x1)。我们可以假设,实际拒绝之间的间隔比重复之间的间隔大得多。
CREATE FUNCTION GetDenialMergingTime()
RETURNS INTEGER UNSIGNED
DETERMINISTIC NO SQL
BEGIN
IF ISNULL(@DenialMergingTime) THEN
RETURN 0;
ELSE
RETURN @DenialMergingTime;
END IF;
END|
CREATE VIEW MergedDenialsViewHelper AS
SELECT MIN(Second.DateTime) AS GroupTime,
First.FeatureId,
First.UserHostId,
SUM(Second.Multiplicity) AS MultiplicitySum
FROM Denial AS First
JOIN Denial AS Second
ON First.FeatureId = Second.FeatureId
AND First.UserHostId = Second.UserHostId
AND First.DateTime >= Second.DateTime
AND First.DateTime - Second.DateTime < GetDenialMergingTime()
GROUP BY First.DateTime, First.FeatureId, First.UserHostId, First.Licenses;
CREATE VIEW MergedDenials AS
SELECT GroupTime,
FeatureId,
UserHostId,
MAX(MultiplicitySum) AS MultiplicitySum
FROM MergedDenialsViewHelper
GROUP BY GroupTime, FeatureId, UserHostId;
然后,要显示用户1和2拒绝功能5和3合并的功能3和4,您要做的就是:
SET @DenialMergingTime := 5;
SELECT GroupTime, FeatureId, UserHostId, MultiplicitySum FROM MergedDenials WHERE UserHostId IN (1, 2) AND FeatureId IN (3, 4);
我使用视图是因为它很容易过滤数据并在jQuery网格中显式使用它,自动排序,限制记录数等。
但这只是一个丑陋的解决方法。有适当的方法来做到这一点吗?