代码之家  ›  专栏  ›  技术社区  ›  Sami

仅当记录具有特定标记时才提取记录

  •  2
  • Sami  · 技术社区  · 9 年前

    我有以下sql查询,用于获取未被注意到的问题,这些问题只包含我最喜欢的标记,另外还包含一些过滤器。

    Live Demo

    此查询有两个主要问题(但可能需要更多改进)

    1. 我应用了一种虚假的技术来实现 在且仅在 =>;(您可以看到这个查询。我必须先使用同一个查询两次,以获得我需要的内容,然后使用非其他过滤器筛选相同的结果,以忽略所有具有除我最喜欢的标记之外的其他标记的问题)。我找不到其他方法来做这件事。
    2. 我已经申请了 distinct 因为它给了我 重复的结果 即使我没有使用任何左连接。我如何区分ID 不使用distinct 关键字

    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
    
    1 回复  |  直到 4 年前
        1
  •  2
  •   Sami    9 年前

    您可以使用 HAVING 条款,如果 ID 是你唯一需要的专栏 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(*) 将返回此的记录总数 身份证件 这个 SUM(CASE..) 将返回没有不需要的标记的记录数。如果它们相等,则意味着只存在所需的标记。