基于ROW_Number的SQL查询不起作用

时间:2022-09-03 15:30:49

Basically I am trying to do a query to a page that holds just an image. I need to provide the tripID number and then the ROWID (as there could be multiple images) to receive a single image. I will be looping until each image is in its corresponding image box in html.

基本上,我正在尝试对只包含图像的页面执行查询。我需要提供tripID数字,然后ROWID(因为可能有多个图像)接收一个图像。我将循环使用,直到每个图像都在相应的html图像框中。

This code doesn't seem to work(I get Invalid column name 'ROWID'), but if I remove the AND ROWID='1' it returns all the images and its row id like this:

这段代码似乎不起作用(我得到无效的列名'ROWID'),但是如果我删除AND ROWID='1'它会返回所有的图像和它的行id如下所示:

ROWID      PHOTO
    1      32jjr3h2jh23hj4h32jh42ll23j42 
    2       HU8308DJAOID9ASIDJI32C89EE29

-

- - - - - -

Select ROW_NUMBER() OVER (ORDER BY Photo ASC) AS ROWID, TBL_Photo.Photo
        From TBL_Photo
        left join TBL_TripDetails
        ON TBL_Photo.TripID=TBL_TripDetails.pkiTripID
        Where pkiTripID = '121' AND ROWID = '1'

1 个解决方案

#1


5  

You can't reference a column alias in the WHERE clause -- you need to use a subquery or a CTE:

您不能在WHERE子句中引用列别名——您需要使用子查询或CTE:

Subquery Example:

SELECT x.rowid,
       x.photo
  FROM (SELECT ROW_NUMBER() OVER (ORDER BY p.photo) AS ROWID, 
               p.photo
          FROM TBL_PHOTO p
     LEFT JOIN TBL_TRIPDETAILS td ON td.pkitripid = p.tripid 
         WHERE td.pkiTripID = '121') x
 WHERE x.rowid = 1

CTE example:

WITH example AS (
        SELECT ROW_NUMBER() OVER (ORDER BY p.photo) AS ROWID, 
               p.photo
          FROM TBL_PHOTO p
     LEFT JOIN TBL_TRIPDETAILS td ON td.pkitripid = p.tripid 
         WHERE td.pkiTripID = '121')
SELECT x.rowid,
       x.photo
  FROM example x
 WHERE x.rowid = 1

Performance

There's no performance difference between the two options, but the WITH syntax isn't supported on all databases.

这两个选项之间没有性能差异,但并不是所有数据库都支持WITH语法。

#1


5  

You can't reference a column alias in the WHERE clause -- you need to use a subquery or a CTE:

您不能在WHERE子句中引用列别名——您需要使用子查询或CTE:

Subquery Example:

SELECT x.rowid,
       x.photo
  FROM (SELECT ROW_NUMBER() OVER (ORDER BY p.photo) AS ROWID, 
               p.photo
          FROM TBL_PHOTO p
     LEFT JOIN TBL_TRIPDETAILS td ON td.pkitripid = p.tripid 
         WHERE td.pkiTripID = '121') x
 WHERE x.rowid = 1

CTE example:

WITH example AS (
        SELECT ROW_NUMBER() OVER (ORDER BY p.photo) AS ROWID, 
               p.photo
          FROM TBL_PHOTO p
     LEFT JOIN TBL_TRIPDETAILS td ON td.pkitripid = p.tripid 
         WHERE td.pkiTripID = '121')
SELECT x.rowid,
       x.photo
  FROM example x
 WHERE x.rowid = 1

Performance

There's no performance difference between the two options, but the WITH syntax isn't supported on all databases.

这两个选项之间没有性能差异,但并不是所有数据库都支持WITH语法。