简体   繁体   中英

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 . 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

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 fetch first . . . offset fetch first . . . offset syntax. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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