我有以下 sql 查询,用于获取未被注意到的问题,这些问题除了我最喜欢的标签之外不包含其他标签,而且它包含更多过滤器。
此查询有两个主要问题(但可能需要更多改进)
- 我应用了一种虚假技术来实现in并且仅在=>(您可以看到查询。我必须首先使用相同的查询两次才能获得我需要的内容,然后过滤相同的结果使用非过滤器,忽略除我最喜欢的标签之外具有任何其他标签的所有问题)。我找不到任何其他方法可以做到这一点。
- 我已经应用了
distinct
,因为即使我没有使用任何左连接,它也会给我重复的结果。如何在不使用 unique 关键字的情况下区分 Id
Select distinct top 100
'http://stackoverflow.com/questions/'+Cast(p.Id as varchar(20)) as ids
from Posts p
Join posttags pt on p.Id=pt.PostId
where AcceptedAnswerId is null
and AnswerCount = 0
and len(body) <2000
and viewCount<30
and DateDiff(hour, p.creationDate, GETDATE())<200
and ClosedDate is null
and p.id not in
(
select p.id as id from posts p join posttags pt
on p.Id=pt.PostId
where pt.tagId != 21 and pt.tagId != 3
and pt.tagId != 9 and pt.tagId != 5
and pt.tagId != 820 and pt.tagId != 2
and pt.tagId != 22 and pt.tagId != 1508
and pt.tagId != 46426 and pt.tagId != 96
and pt.tagId != 363
and AcceptedAnswerId is null
and AnswerCount = 0
and len(body) <3000
and viewCount<30
and DateDiff(hour, p.creationDate, GETDATE())<200
and ClosedDate is null
)
order by ids
--21 mysql --3 javascript --9 c# --5 php --820 jquery
--2 html --22 sql --1508 json --46426 nodejs--96 asp.net
--363 ajax
最佳答案
如果 ID
是您唯一需要的列,则可以使用 HAVING
子句,并使用 IN()
来避免同一列出现多个条件栏目:
在此处查看现场演示 Response waiting questions
Select distinct top 100
'http://stackoverflow.com/questions/'+Cast(p.Id as varchar(20)) as ids
from Posts p
Join posttags pt
on p.Id=pt.PostId
where AcceptedAnswerId is null
and AnswerCount <3
and len(body) <2000
and viewCount<30
and DateDiff(hour, p.creationDate, GETDATE())<200
and ClosedDate is null
GROUP BY 'http://stackoverflow.com/questions/'+Cast(p.Id as varchar(20))
HAVING COUNT(*) = SUM(CASE WHEN tagID IN(21,3,9,820,2,22,1508,46426,96,363) THEN 1 ELSE 0 END)
COUNT(*)
将返回此 ID
的记录总数,SUM(CASE..)
将返回该数字没有您不需要的标签的记录。如果它们相等,则意味着仅存在所需的标签。
关于sql - 仅当记录具有特定标签时才获取记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39329687/