SQL数据查询错误:关键字“ join”附近的语法不正确

时间:2018-10-01 03:34:30

标签: sql

我正在尝试开发一个查询: https://data.stackexchange.com/stackoverflow/query/new

也许你们可以帮忙:

  1. 鉴于用户当前的热门标签,我想找到类似的问题,
  2. 具有最高的观看次数(即大于500),但也有
  3. 少于20个答案。
  4. 按观看次数排序

第二段中的某个地方,这里的联接查询附近有错误发生:join #tags t on t.TagId = TagId,说:关键字'join'附近的语法不正确。

非常感谢您的帮助:

        DECLARE @UserId int = ##UserId##

        create table #tags (TagId int, [Count] int)
        insert #tags 
        SELECT TOP 20 
        TagId,
        COUNT(*) AS UpVotes 
        FROM Tags
          INNER JOIN PostTags ON PostTags.TagId = Tags.id
          INNER JOIN Posts ON Posts.ParentId = PostTags.PostId
          INNER JOIN Votes ON Votes.PostId = Posts.Id and VoteTypeId = 2
        WHERE 
          Posts.OwnerUserId = @UserId
        GROUP BY TagId
        ORDER BY UpVotes DESC  

        select top 2000 [Post Link], Views
        join #tags t on t.TagId = TagId  
        where
          ViewCount > 500 and AnswerCount < 20
        order by ViewCount desc 

更新

DECLARE @UserId int = ##UserId##

    create table #tags (TagId int, [Count] int)
    insert #tags 
    SELECT TOP 20 
    TagId,
    COUNT(*) AS UpVotes 
    FROM Tags
      INNER JOIN PostTags ON PostTags.TagId = Tags.id
      INNER JOIN Posts ON Posts.ParentId = PostTags.PostId
      INNER JOIN Votes ON Votes.PostId = Posts.Id and VoteTypeId = 2
    WHERE 
      Posts.OwnerUserId = @UserId
    GROUP BY TagId
    ORDER BY UpVotes DESC  

    select top 2000 [Post Link], Views
    from Posts
    join #tags t on t.TagId = posts.TagId  
    where
      posts.ViewCount > 500 and posts.AnswerCount < 20
      order by posts.ViewCount desc 

,但是Posts表具有标签列:nvarchar(250)。我该如何匹配?

2 个答案:

答案 0 :(得分:2)

我认为您在加入之前错过了“ FROM”语句

答案 1 :(得分:1)

表变量是批处理范围变量(t1是另一个临时表中的变量,仅以temp中的t1为例)。

select top 2000 [Post Link], Views
        join #tags t, #tags t1 on t.TagId = t1.TagId  
        where
          t.ViewCount > 500 and t.AnswerCount < 20
        order by t.ViewCount desc