0

我想要的是,如果不将任何值传递给变量,那么它应该显示表中的所有值,而如果我将值传递给变量,那么它应该在该参数的过滤器上提供数据。

SET @groupname := 'MidasGoogleAppsUsers';
IF @groupname = '' THEN
SELECT t.GroupName AS GroupName, t.GroupName AS ApplicationName, t.UserName
FROM UserApplication t;

ELSE

SELECT t.GroupName AS GroupName, t.GroupName AS ApplicationName, t.UserName
    FROM UserApplication t
    WHERE t.GroupName = @groupname;

END IF;

下面是表结构:

CREATE TABLE userapplication
            (`ID` INT,
             `ApplicationName` VARCHAR(100),
             `GroupName` VARCHAR(100),
             `UserName` VARCHAR(100))
4

3 回答 3

1

尝试这个:

    SELECT t.GroupName AS GroupName, t.GroupName AS ApplicationName, t.UserName
    FROM UserApplication t
    WHERE @Groupname is null or @Groupname = '' or t.GroupName = @groupname;

您可以使用where子句中的逻辑来执行此操作。你完全不需要if

添加更多条件:

    SELECT t.GroupName AS GroupName, t.GroupName AS ApplicationName, t.UserName
    FROM UserApplication t
    WHERE (@Groupname is null or @Groupname = '' or t.GroupName = @groupname) and
          (@UserName is null or @UserName = '' or t.UserName= @UserName );
于 2013-06-10T13:34:12.580 回答
0

@groupname的可能不是''但是null。您不需要if使用该查询

SELECT t.GroupName AS GroupName, t.GroupName AS ApplicationName, t.UserName
FROM UserApplication t
WHERE t.GroupName = @groupname 
OR @groupname IS NULL
于 2013-06-10T13:33:37.070 回答
0

据我所知,MySQL 不支持默认参数。有几个关于此的 StackOverflow 帖子。所以看起来你必须为@groupName.

您可以像这样组合两个查询:

SELECT t.GroupName AS GroupName, t.GroupName AS ApplicationName, t.UserName
FROM UserApplication t
WHERE @groupname = '' OR t.GroupName = @groupname;

或者,如果您将使用NULLfor @groupName(我建议这样做):

SELECT t.GroupName AS GroupName, t.GroupName AS ApplicationName, t.UserName
FROM UserApplication t
WHERE @groupname IS NULL OR t.GroupName = @groupname;
于 2013-06-10T13:33:53.647 回答