简体   繁体   English

sql如何使用行号进行内部联接

[英]sql how to do an inner join with row number

I am trying to do an inner join with row number using dapper MSSQL and I keep getting this exception Additional information: The column 'id' was specified multiple times for 'threadem . 我正在尝试使用dapper MSSQL与行号进行内部联接,并且不断收到此异常。 附加信息:为'threadem'多次指定了'id'列 I have 2 tables threads and zips and they both have a primary key of id I don't know if that has to do with it, this is my code 我有2个表线程和zip,它们都具有id的主键,我不知道这是否与它有关,这是我的代码

SELECT z.*,
       t.*
FROM   (SELECT ROW_NUMBER() OVER (ORDER BY t.activities DESC) AS Row,
               z.*,
               t.*
        FROM   threads t
               INNER JOIN zips z
                 ON z.city = @Ucity
                    AND z.state = @Ustate
        WHERE  t.latitudes >= z.ThirtyLatMin
               AND z.ThirtyLatMax >= t.latitudes
               AND t.longitudes >= z.ThirtyLonMin
               AND z.ThirtyLonMax >= t.longitudes) AS threadem
WHERE  ROW >= 1
       AND Row <= 5 

what can I fix above to stop getting this error 我该如何解决才能停止收到此错误

First, if you are using SQL Server 2012+, you can use fetch first . . . offset 首先,如果您使用的是SQL Server 2012+,则可以先使用fetch first . . . offset fetch first . . . offset fetch first . . . offset syntax. fetch first . . . offset语法。 This is more convenient than row number. 比行号更方便。

The best way to solve your problem is to list all the columns you need explicitly. 解决问题的最佳方法是显式列出所有需要的列。 Then, if two columns from the tables have the same names, use an alias to rename them. 然后,如果表中的两列具有相同的名称,请使用别名重命名它们。 Something like: 就像是:

SELECT t.*
FROM   (SELECT ROW_NUMBER() OVER (ORDER BY t.activities DESC) AS Row,
               z.zcol1, z.zcol2, . . .,
               t.tcol1, t.zcol2, . . 
        FROM threads t INNER JOIN
             zips z
             ON z.city = @Ucity AND z.state = @Ustate
        WHERE t.latitudes >= z.ThirtyLatMin AND
              z.ThirtyLatMax >= t.latitudes AND
              t.longitudes >= z.ThirtyLonMin AND
              z.ThirtyLonMax >= t.longitudes
      ) t
WHERE ROW >= 1 AND Row <= 5 ;

If you don't want row as a returned column in the outer query, then you need to list all the columns that you do want in the outer select . 如果你不想row在外部查询返回的列,那么你需要列出所有想在外部列select

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM