嵌套查询中的SQL限制,排序和连接

时间:2013-07-03 10:12:47

标签: sql

我有这个问题:

Select VENDOR, CODE, TABOF.OFID,DATEI,DATEF,VARR,VARRT,DESEXT
from (
        Select A_IND,A_COD,A_DES,A_FX,A_ML,
               OFID,DATEI,DATEF,VARR,VARRT,FLAGD,VENDOR
        from ANTAB
        join TABOF
            on (ANTAB.A_COD = TABOF.VENDOR) 
            where
                A_FX <> '' and A_ML <> '' and 
                A_DES <> '' and A_COD <> '' and
                A_IND <> '' and
                A_FX < (47.7 + 0.5) and
                A_FX > (47.7 - 0.5) and
                A_ML < (15.5 + 0.5) and
                A_ML > (15.5 - 0.5) 
            order by
                sqrt(power((A_FX - 47.7),2) + 
                    power((A_ML - 15.5),2))
            limit 1
     )
join OF_MNTAB
    on (OF_MNTAB.OFID = OFTAB.OFID)
    where 
        DATEI <= getdate() and
        DATEF >= getdate() and
        OFTAB.FLAGD = 0 and
        CODE not in ('MANU','TRAN') and
        VENDOR = A_COD
    order by DATEI desc

但是当我尝试执行它时它会一直给我错误: “limit”附近的语法错误,如果我删除限制选项,它会在下一行的连接附近给出语法错误。 我是一个sql noob,这对我来说是一个复杂的查询.. 我做错了什么?

2 个答案:

答案 0 :(得分:0)

你不能在子查询中使用限制。你错过了内联视图的别名

Select VENDOR, CODE, TABOF.OFID,DATEI,DATEF,VARR,VARRT,DESEXT
from (
        Select A_IND,A_COD,A_DES,A_FX,A_ML,
               OFID,DATEI,DATEF,VARR,VARRT,FLAGD,VENDOR
        from ANTAB
        join TABOF
            on (ANTAB.A_COD = TABOF.VENDOR) 
            where
                A_FX <> '' and A_ML <> '' and 
                A_DES <> '' and A_COD <> '' and
                A_IND <> '' and
                A_FX < (47.7 + 0.5) and
                A_FX > (47.7 - 0.5) and
                A_ML < (15.5 + 0.5) and
                A_ML > (15.5 - 0.5) 
            order by
                sqrt(power((A_FX - 47.7),2) + 
                    power((A_ML - 15.5),2))

     ) OFTAB
join OF_MNTAB
    on (OF_MNTAB.OFID = OFTAB.OFID)
    where 
        DATEI <= getdate() and
        DATEF >= getdate() and
        OFTAB.FLAGD = 0 and
        CODE not in ('MANU','TRAN') and
        VENDOR = A_COD
    order by DATEI desc

答案 1 :(得分:0)

根据Adaptive Server Anywhere SQL User’s Guide,第251页,您可以使用TOP,而不是LIMIT。因此,请移除LIMIT 1并添加TOP 1

Select VENDOR, CODE, TABOF.OFID,DATEI,DATEF,VARR,VARRT,DESEXT
from (
        Select TOP 1
               A_IND,A_COD,A_DES,A_FX,A_ML,
               OFID,DATEI,DATEF,VARR,VARRT,FLAGD,VENDOR
...

正如@chetan正确指出的那样,还有一个别名缺失。