首先,感谢您抽出时间帮助我!
我有以下(示例)表:
UNDEAD
i <= 0
现在我想要这样的事情:
User UserGroup IsAdmin
_____________________________
foo zombie N
bar skeletton N
blub vampire Y
- &GT;当然,这是&#34;吸血鬼&#34;
现在我的问题: 管理员应该获取所有组,因此不同用户的结果是:
我如何实现这一目标?
答案 0 :(得分:0)
SELECT UserGroup
FROM UNDEAD
WHERE User = blub
UNION
SELECT DISTINCT UserGroup
FROM UNDEAD
WHERE
(
SELECT IsAdmin
FROM UNDEAD
WHERE User = blub
) = 'Y'
答案 1 :(得分:0)
您可以使用UNION
来实现此目的。首先,选择所有非管理员用户及其关联组。其次,您需要执行自我联接,为每个管理员用户返回每个组,并UNION
结果:
SELECT UserName ,
UserGroup
FROM undead
WHERE IsAdmin = 'N'
UNION
SELECT u1.UserName,u2.UserGroup
FROM undead u1, undead u2
WHERE u1.IsAdmin='Y'
请注意,我更改了User
列的名称,因为它是保留关键字。请参阅下面我创建的设置脚本。
CREATE TABLE undead(
UserName VARCHAR2(100),
UserGroup VARCHAR2(100),
IsAdmin VARCHAR2(100));
INSERT INTO undead(UserName, UserGroup, IsAdmin) VALUES('foo','zombie','N');
INSERT INTO undead(UserName, UserGroup, IsAdmin) VALUES('bar','skeleton','N');
INSERT INTO undead(UserName, UserGroup, IsAdmin) VALUES('blub','vampire','Y');
答案 2 :(得分:0)
我认为不需要union
。
select distinct UserGroup
from undead
where [User] = 'bulb' or (select IsAdmin from undead where [User] = 'bulb') = 'Y'
Herzlich Willkommen在StackOverflow aus Athen!
答案 3 :(得分:0)
您甚至可以使用动态SQL查询。
<强>查询强>
set @query = null;
set @user = 'foo';
select distinct case when `User` = @user and `IsAdmin` = 'Y'
then 'select distinct `UserGroup` from `UNDEAD`;'
else concat('select `UserGroup` from `UNDEAD` where `User` = ''', @user, ''';') end
into @query
from `UNDEAD`
where `User` = @user;
prepare stmt from @query;
execute stmt;
deallocate prepare stmt;
这里基于@user值,将执行sql查询。它会检查IsAdmin
。如果是Y
,那么该特定用户的所有唯一UserGroup
其他UserGroup
。
<强> SQL Fiddle demo
强>
答案 4 :(得分:0)
希望这会有所帮助
SELECT *
FROM UNDEAD S
WHERE (CASE
WHEN 'blub' = (SELECT DISTINCT S1.USER
FROM UNDEAD S1
WHERE S1.ISADMIN = 'Y') THEN
'TRUE'
END) = 'TRUE'
UNION
SELECT * FROM UNDEAD S WHERE S.USER = 'blub'
您可以更改代码中的值(blub,foo,bar)以进行检查。它为ADMIN Y提供所有行,特定于N