使用SQL获取在“IN”中具有两个值的记录

时间:2012-04-23 18:00:43

标签: sql relational-division

我需要一个SQL语句来从数据库中提取具有附件标记的那些申请人。如果我想要7或8作为附件标签的aaplicant但是我需要具有这两个标签的申请人,则belowq语句可以正常工作。

select distinct(a.id) from applicant a
join applicantdeployment ad on a.id = ad.applicantid
join ApplicantAttachment at on a.id = at.applicantid
where a.applicanttype = 'TCN/LN' and ad.groundlocation in (4,8,14) and ad.deploymentstatus =1
and ad.trainingdeploymentstatus = 6 and at.tag in (7,8)

例如,从下面的集合我只想要显示ids 7332,7451和7449。

ID标记
7328 8
7328 8
7332 8
7332 7
7337 7
7449 8
7449 7
7451 8
7453 7
7451 7

谢谢!

6 个答案:

答案 0 :(得分:5)

你需要在下面做,而不是分开:

GROUP BY a.id HAVING COUNT(a.id) = 2  

答案 1 :(得分:1)

在您的样本数据中,是否也不应选择7451?您需要修改以下代码以适合您的查询,但请尝试以下操作:

CREATE TABLE #Temp
(
    ID INT,
    Tag INT
)

INSERT INTO #Temp
(
    ID,
    Tag
)
SELECT 7328, 8 UNION
SELECT 7332, 8  UNION
SELECT 7332, 7  UNION
SELECT 7337, 7  UNION
SELECT 7449, 8  UNION
SELECT 7449, 7  UNION
SELECT 7451, 8  UNION
SELECT 7453, 7  UNION
SELECT 7451, 7

select distinct(ad.id) from #Temp ad
join #Temp at on ad.id = at.id
AND ad.Tag != at.Tag
where at.tag in (7,8)
AND ad.Tag IN (7, 8)

答案 2 :(得分:1)

如果将IN列表项放入名为#Tags的表中,这将起作用,如果标签数量发生变化,则无需重写查询。

select distinct(#Temp.ID)
from #Temp
where not exists (
  select * from #Tags
  where not exists (
    select * from #Temp as TempCopy
    where TempCopy.Tag = #Tags.Tag
    and TempCopy.ID = #Temp.ID
  )
)  

在英语中,这会选择缺少任何所需标签的ID。

答案 3 :(得分:0)

尝试:

select distinct(a.id)
from applicant a
join applicantdeployment ad on a.id = ad.applicantid
join (select applicantid from applicantattachment at1
join applicantattachment at2 on at1.applicantid=at.applicantid
where at1.tag=7 and at2.tag=8) at
on a.id = at.applicantid
where a.applicanttype = 'TCN/LN'
and ad.groundlocation in (4,8,14)
and ad.deploymentstatus =1
and ad.trainingdeploymentstatus = 6

将申请人附表加入自己,只获得相关的申请表。

答案 4 :(得分:0)

您可以两次加入ApplicationAttachment表,以确保两个标记都存在。这样你就可以避免使用DISTINCT和GROUP BY。

SELECT a.id
FROM applicant a
JOIN applicantdeployment ad ON a.id = ad.applicantid
JOIN ApplicantAttachment at7 ON a.id = at7.applicantid AND at7.tag = 7
JOIN ApplicantAttachment at8 ON a.id = at8.applicantid AND at8.tag = 8
WHERE a.applicanttype = 'TCN/LN' 
AND ad.groundlocation IN (4,8,14)
AND ad.deploymentstatus = 1
AND ad.trainingdeploymentstatus = 6

答案 5 :(得分:-2)

select distinct(a.id) from applicant a
join applicantdeployment ad on a.id = ad.applicantid
join ApplicantAttachment at on a.id = at.applicantid
where a.applicanttype = 'TCN/LN' and ad.groundlocation in (4,8,14) and ad.deploymentstatus =1
and ad.trainingdeploymentstatus = 6 and at.tag in (7,8) and a.id IN (7332,7449);