我有以下SQL:
declare @Users table (
Id int not null primary key clustered (Id),
[Name] nvarchar(255) not null
);
declare @Skills table (
SkillId int not null primary key clustered (SkillId)
);
declare @UserSkills table (
UserId int not null,
SkillId int not null,
primary key clustered (UserId, SkillId)
);
insert into @Users
values (1, 'Jonh'), (2, 'Mary');
insert into @Skills
values (148), (149), (304), (305);
insert into @UserSkills
values (1, 149), (1, 305), (2, 148), (2, 149);
select u.Id, u.Name
from @Users as u
inner join @UserSkills as us
on u.Id = us.UserId
where us.SkillId in (149, 305)
group by u.Id, u.Name
having count(*) = 2
我正在按预期获得John用户。
但是在实际代码中,用户有40列。
是否可以使用select / group by来使用所有列,而无需单独枚举所有列?
答案 0 :(得分:3)
加入之前:
select u.*
from @Users u join
(select us.UserId
from @UserSkills us
where us.SkillId in (149, 305)
group by us.UserId
having count(*) = 2
) us
on u.Id = us.UserId