这里我有两个表委员会大学和学院。 表的结构是这样的
committee_colleges
committeeCollegeId collegeId committeeMemberId
1 2 1
2 2 2
3 3 2
我从委员会成员表中存储委员会会员。一个学院可以有多个委员会成员。如何查询只显示分配给特定委员会成员的大学。 例如,如果id = 2的committeeMember已经登录,我想通过id = 2,3显示大学。
在大学的桌子上我喜欢这个,
collegeId typeName
1 AICTE
2 NCTE
3 NTCS
这是委员会成员表
committeeMemberId name
1 xyz
2 abc
现在我正在写这样的东西,但我知道它错了,因为我不知道如何从大学学习桌上拿走它,因为我正在展示学院的细节。
SELECT cc.committeeCollegeId as committeeCollegeId,
c.collegeId as collegeId,
cc.committeeMemberId as committeeMemberId
FROM committee_college as cc
left outer join College as c
on cc.collegeId = c.collegeId
where cc.committeeMemberId=:committeeMemberId
order by cc.committeeCollegeId asc
任何人都可以根据其对特定委员会成员的任命来说明如何展示大学吗?
答案 0 :(得分:1)
你很接近,你需要INNER JOIN
而不是LEFT JOIN
:
SELECT DISTINCT C.typeName --<<== put here all the columns that you want in output
FROM committee_colleges CC
INNER JOIN college C
ON C.collegeId = CC.collegeId
WHERE CC.committeeMemberId = 2 --<<== your input parameter
编辑:添加了DISTINCT
希望它有所帮助。
答案 1 :(得分:0)
您可以在下面的sql语句中使用相同的
DECLARE @committeeMemberId INT = 2 -- Id of Committee member
;WITH CTE_MemberCommittee AS
(
SELECT CollegeId
FROM committee_colleges
WHERE committeeMemberId = @committeeMemberId
)
SELECT collegeId, typeName
FROM college
WHERE collegeId IN (SELECT CollegeId FROM CTE_MemberCommittee)
答案 2 :(得分:0)
试试这个:
DECLARE @LoginCommitteeMemberId INT=2
SELECT t2.Name AS MemberName,
t3.TypeName AS CollageName
FROM committee_college t1
INNER JOIN Committee_Member t2
ON t1.committeeMemberId = t2.committeeMemberId
INNER JOIN College as t3
ON t1.collegeId = t3.collegeId
WHERE t1.committeeMemberId = @LoginCommitteeMemberId
答案 3 :(得分:0)
您可以使用简单的内部联接,
如果你想基于memberId的collegename使用以下查询,
select a.collegeid,a.typeName from
college a, committee_colleges b, committe_member c
where a.collegeid = b.collegeid and
b.committeememberid = c.committeeMemberId
and c.committeeMemberId = '2'
如果你想根据committemember名称使用collegename,那么使用以下查询,
select a.collegeid,a.typeName from
college a, committee_colleges b, committe_member c
where a.collegeid = b.collegeid and
b.committeememberid = c.committeeMemberId
and c.Name = 'xyz'
希望它会有所帮助。