我想弄清楚如何解决这个问题。
选择曾为IBM和Microsoft工作过的候选人。
与数据库关联的表包括
Candidate(Id,Name)
Company(Id,Name)
hasWorkedFor(CandidateId,CompanyId)
CandidateId和Company Id是Candidate表和Company表的外键。
我得到的查询是:
SELECT Candidate.Name
FROM Candidate x, Candidate y, Company c1, Company c2, hasWorkedFor
WHERE x.Id = Id
AND c1.Id = CompanyId
AND c1.Name = "Microsoft"
AND c2.Id = CompanyId
AND c2.Name = "IBM";
任何帮助都将不胜感激。
答案 0 :(得分:2)
试试这个:
select Candidate.* from Candidate inner join (
select CandidateId from hasWorkedFor inner join Company
on hasWorkedFor.CompanyId = Company.id
where Company.name in ('IBM', 'Microsoft')
group by CandidateId
having count(distinct CompanyId) = 2
)t
on Candidate.Id = t.CandidateId
请注意,此查询还会为那些可能适用于其他公司的候选人提供 。
如果您需要为IBM和Microsoft工作 的候选人,那么您可以使用:
select Candidate.* from Candidate inner join (
select t1.CandidateId from (
select CandidateId from hasWorkedFor inner join Company
on hasWorkedFor.CompanyId = Company.id
where Company.name in ('IBM', 'Microsoft')
group by CandidateId
having count(distinct CompanyId) = 2
)t1 inner join(
select CandidateId from hasWorkedFor
inner join Company
on hasWorkedFor.CompanyId = Company.id
group by CandidateId
having count( distinct CompanyId ) = 2
) t2 on t1.CandidateId = t2.CandidateId
)t
on Candidate.Id = t.CandidateId
答案 1 :(得分:0)
尝试此操作,如有任何疑问,请与我联系。
select a.name as candiate_name
from
candidate a
left join
hasworkedfor b
on a.id = b.candidateid
left join
company c
on b.companyid = c.id
where c.name = 'Microsoft' and c.name = 'IBM';
答案 2 :(得分:0)
试试这段代码:
select candidate.name from candidate
inner join hasworkedfor
on candidate.id = hasworkedfor .candidateid inner join company
on hasworkedfor .companyid = company.id
where company.name = 'Microsoft' and company.name = 'IBM'
答案 3 :(得分:0)
SELECT ca.Name FROM Candidate ca
WHERE ca.Id IN (SELECT hw.CandidateId FROM hasWorkedFor hw
LEFT OUTER JOIN Company co ON hw.CompanyId = co.Id WHERE co.Name = 'Microsoft') AND
ca.Id IN (SELECT hw.CandidateId FROM hasWorkedFor hw
LEFT OUTER JOIN Company co ON hw.CompanyId = co.Id WHERE co.Name = 'IBM')
或
SELECT ca.Name FROM Candidate ca
WHERE COUNT(SELECT DISTINCT hw.CompanyId FROM hasWorkedFor hw
LEFT OUTER JOIN Company co ON hw.CompanyId = co.Id
WHERE (co.Name = 'Microsoft' OR co.Name = 'IBM') AND hw.CandidateId = ca.Id) = 2
答案 4 :(得分:0)
select * from Candidate c where
exists(select * from hasWorkedFor w where w.CandidateId=c.Id and w.CompanyId = 'Microsoft')
and exists(select * from hasWorkedFor w where w.CandidateId=c.Id and w.CompanyId = 'IBM')
换句话说,从Candidate中选择
答案 5 :(得分:0)
我的解决方案:
SELECT ca.Name
FROM Company cm
JOIN hasWorkedFor wk ON cm.Id = wk.CompanyId
JOIN Candidate ca ON wk.CandidateId = ca.Id
WHERE cm.Name IN ('IBM', 'Microsoft')
GROUP BY ca.Id,ca.Name
HAVING COUNT(*) = 2