我有三张桌子
我想写一个查询来查找具有相同技能的用户 例如,这是UserSkill表中的示例数据
U-id S-id
1 1
1 2
1 7
2 1
2 6
所以结果会像这样
UserName1 UserName2 SkillName
A B Java
ad这是我的查询
{select ui.UserName,ui2.UserName,SkillName
from
UserSkill us1 inner join UserSkill us2
on us1.SkillID = us2.SkillID and us1.UserID <> us2.UserID
inner join UsersINFO UI
on ui.UserID = us1.UserID
inner join UsersINFO ui2
on ui2.UserID = us2.UserID
inner join Skill s
on s.SkillID = us2.SkillID}
我想知道是否有人知道更好的方式来编写查询
答案 0 :(得分:3)
您只需在末尾添加Where ui.UserName<ui2.UserName
select ui.UserName,ui2.UserName,SkillName
from
UserSkill us1 inner join UserSkill us2
on us1.SkillID = us2.SkillID and us1.UserID <> us2.UserID
inner join UsersINFO UI
on ui.UserID = us1.UserID
inner join UsersINFO ui2
on ui2.UserID = us2.UserID
inner join Skill s
on s.SkillID = us2.SkillID
Where ui.UserName<ui2.UserName
输出
UserName UserName SkillName
A B Java
现场演示
答案 1 :(得分:1)
您查询的结果非常混乱。它报告A,B,java和B,A,java。
declare @J table (uid int, sid int, primary key (uid, sid));
insert into @J values
(1, 1)
, (1, 2)
, (1, 7)
, (2, 1)
, (2, 6)
, (3, 1)
, (3, 2);
declare @N table (id int primary key, name varchar(10));
insert into @N values
(1, 'bob')
, (2, 'ted')
, (3, 'mac');
select j1.sid, n1.name, n2.name
from @J j1
join @J j2
on j2.sid = j1.sid
and j2.uid <> j1.uid
join @N n1
on n1.id = j1.uid
join @N n2
on n2.id = j2.uid
order by j1.sid, j1.uid, j2.uid;
sid name name
----------- ---------- ----------
1 bob ted
1 bob mac
1 ted bob
1 ted mac
1 mac bob
1 mac ted
2 bob mac
2 mac bob
即使您更换&lt;&gt;用&gt;当你有超过2个具有相同技能时,它仍然是凌乱的。
select j1.sid, n1.name, n2.name
from @J j1
join @J j2
on j2.sid = j1.sid
and j2.uid > j1.uid
join @N n1
on n1.id = j1.uid
join @N n2
on n2.id = j2.uid
order by j1.sid, j1.uid, j2.uid;
sid name name
----------- ---------- ----------
1 bob ted
1 bob mac
1 ted mac
2 bob mac
我建议你不要成对报告
select *
from ( select j1.sid, n1.name
, count(*) over (partition by j1.sid) as cnt
from @J j1
join @N n1
on n1.id = j1.uid
) t
where t.cnt > 1
order by t.sid, t.name;
sid name cnt
----------- ---------- -----------
1 bob 3
1 mac 3
1 ted 3
2 bob 2
2 mac 2
答案 2 :(得分:-1)
以下内容返回具有相应技能的所有用户对以及该技能:
select ui.name, us2.name, s.s_name
from userskill us join
userskill us2
on us.sid = us2.sid join
skills s
on s.sid = us.sid join
userinfo ui
on ui.uid = us.uid join
userinfo ui2
on ui2.uid = us2.uid
where us.uid <> us2.uid;