我有3个表:用户,项目和锁定项目
我想显示项中的所有内容,但如果用户想要隐藏项目,那么我将其userid和itemid添加到锁定列表
[users]
userid
username
[items]
itemid
itemname
[lockeditems]
itemid
userid
SQLSERVER, 如何选择所有[项目],但不要通过[itemid]和[userid]显示项目锁定列表中的项目?
谢谢,抱歉没有格式化
答案 0 :(得分:1)
MS SQL Server 2008架构设置:
CREATE TABLE users
([userid] int, [username] varchar(4))
;
INSERT INTO users
([userid], [username])
VALUES
(1, 'John'),
(2, 'Mary')
;
CREATE TABLE items
([itemid] int, [itemname] varchar(6))
;
INSERT INTO items
([itemid], [itemname])
VALUES
(1, 'saw'),
(2, 'hammer')
;
CREATE TABLE lockeditems
([itemid] int, [userid] int)
;
INSERT INTO lockeditems
([itemid], [userid])
VALUES
(1, 1)
;
查询1 :
select u.userid, i.*
from users u
cross join items i
left outer join lockeditems l on u.userid = l.userid and i.itemid = l.itemid
where l.userid is null
<强> Results 强>:
| USERID | ITEMID | ITEMNAME |
|--------|--------|----------|
| 1 | 2 | hammer |
| 2 | 1 | saw |
| 2 | 2 | hammer |
答案 1 :(得分:1)
假设你有一个变量中的用户,比如说@TheUserId
,那么这是对not exists
子句的一个很好的用法:
select i.*
from items i
where not exists (select 1
from lockeditems li
where li.userid = @TheUserId and
li.itemid = i.itemid
);
答案 2 :(得分:0)
这应该这样做:
SELECT *
FROM Users u
CROSS JOIN Items i
WHERE NOT EXISTS
(SELECT *
FROM lockeditems li
WHERE li.userID = u.userid AND i.itemid = li.itemid);
Except也可以使用
SELECT u.UserId, i.ItemId
FROM Users u
CROSS JOIN Items i
EXCEPT
SELECT li.UserId, li.ItemID
FROM lockeditems li;
答案 3 :(得分:0)
CREATE TABLE users (
userid int,
username varchar(20))
CREATE TABLE items (
itemid int,
itemname varchar(20))
CREATE TABLE lockeditems (
itemid int,
userid int)
INSERT INTO users VALUES (1,'Adam'),(2,'Johan'),(3,'Jennifer'),(4,'Rajanand'),(5,'Jason')
INSERT INTO items VALUES (10,'Keyboard'),(20,'Mouse'),(30,'CPU'),(40,'Hard drive'),(50,'RAM')
INSERT INTO lockeditems VALUES (30,3),(50,5)
SELECT * FROM users WHERE userid NOT IN (SELECT userid FROM lockeditems)
SELECT * FROM items WHERE itemid NOT IN (SELECT itemid FROM lockeditems)