我在SQL中有3个表
用户
UserID|UserName|password
1:John:abc123
2:Sara:asdfr
AppRights
apprightkey|description
removedata:Can Remove Data
adddata:Can Insert New Data
viewdata:Only Can View Data
UserRights
userid|rightkey
1:adddata
1:removedata
2:removedata
以下是我想通过插入用户ID来获取AppRights表中的描述的问题,但只有UserRights表中可用的那些。
我也尝试了这样但结果没有返回任何内容
select Decsription
from AppRights
where AppRigthKey = (select RrightKey from UserRights where userid=1);
答案 0 :(得分:0)
试试这个,
select Decsription
from AppRights
where AppRigthKey = (select RrightKey from UserRights);
我认为,你的查询中有一些拼写错误。 试试我的回答:
DECLARE @Users TABLE(UserID INT, UserName VARCHAR(10),password VARCHAR(10))
INSERT INTO @Users VALUES(1,'John','abc123')
INSERT INTO @Users VALUES(2,'Sara','asdfr')
DECLARE @AppRights TABLE(apprightkey VARCHAR(100),description VARCHAR(100))
INSERT INTO @AppRights VALUES('removedata','Can Remove Data')
INSERT INTO @AppRights VALUES('adddata','Can Insert New Data')
INSERT INTO @AppRights VALUES('viewdata','Only Can View Data')
DECLARE @UserRights TABLE(userid INT,rightkey VARCHAR(100))
INSERT INTO @UserRights VALUES(1,'adddata')
INSERT INTO @UserRights VALUES(1,'removedata')
INSERT INTO @UserRights VALUES(2,'removedata')
select description
from @AppRights
where apprightkey IN (select rightkey from @UserRights where userid=1);
请尝试以下表格:
select description
from AppRights
where apprightkey IN (select rightkey from UserRights where userid=1);
答案 1 :(得分:0)
这是有效的语法:
select Decsription from AppRights
where AppRigthKey = (select RrightKey from UserRights);
但是您确实需要确保子查询只返回一个值,这是确保这一点的一种方法:
select Decsription from AppRights
where AppRigthKey = (select max(RrightKey) from UserRights);
或者,使用IN可能会有所帮助,因为这允许子查询返回多个值。
select Decsription from AppRights
where AppRigthKey IN (select RrightKey from UserRights);
然而,这也可能使查询显示更多行。
答案 2 :(得分:0)
请注意,您的子查询应返回一行
SELECT field1 from TABLE1 where field1 = (SELECT field2 from TABLE2)
或者如果它返回更多那个你可以使用IN语句
SELECT field1 from TABLE1 where field1 IN (SELECT field2 from TABLE2)
在你的情况下可能就像
select Decsription from AppRights where AppRigthKey IN (select RrightKey from UserRights);