从具有条件的三个表中获取数据

getting data from three tables with conditions

我在 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
用户权限
userid|rightkey
1:adddata
1:removedata
2:removedata

这是我想通过插入用户 ID 从 AppRights table 获取描述的问题,但只有那些在 UserRights table.
中可用的描述 我也这样试过,但它没有返回任何结果。
select Decsription from AppRights where AppRigthKey = (select RrightKey from UserRights where userid=1);

试试这个,

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);

这是有效的语法:

select Decsription from AppRights 
where AppRigthKey = (select RrightKey from UserRights);

但是您需要确保只有一个值被子查询return编辑,确保这一点的一种方法是:

select Decsription from AppRights 
where AppRigthKey = (select max(RrightKey) from UserRights);

或者,使用 IN 会有所帮助,因为这允许子查询 return 多个值。

select Decsription from AppRights 
where AppRigthKey IN (select RrightKey from UserRights);

然而,这也可能导致查询显示更多行。

请注意你的子查询应该return一行

SELECT field1 from TABLE1 where field1 = (SELECT field2 from TABLE2)

或者如果 return 多于一个,您可以使用 IN 语句

SELECT field1 from TABLE1 where field1 IN (SELECT field2 from TABLE2)

你的情况可能是这样

select Decsription from AppRights where AppRigthKey IN (select RrightKey from UserRights);