SQL子查询中的语法错误

时间:2012-08-29 05:22:26

标签: mysql syntax

我收到语法错误,任何人都可以告诉我为什么?

SELECT  c.clientid, c.clientname, c.billingdate, 
      (SELECT TOP 1 previousbalance FROM invoice i 
          WHERE i.client = c.clientid ORDER BY i.invoiceid DESC) AS remaining 
FROM client c 
ORDER BY clientname

辅助选择正在做的是在发票表中获取clientid的最新记录。

该计划 - HediSQl

SQL

这是错误:

  

SQL错误(1064):您的SQL语法中有错误;查看与您的MySQL服务器版本对应的手册,以便在'1 previousbalance FROM invoice i WHERE i.client = c.clientid ORDER BY i.invoicei'附近使用正确的语法*第1行* /

3 个答案:

答案 0 :(得分:3)

只是猜测,但可能表示您应该将TOP 1替换为LIMIT 1WHERE ROWNUM < 2 LIMIT 1。你在用什么类型的数据库?

答案 1 :(得分:1)

您只需使用LIMIT代替TOP,就像这样:

SELECT  c.clientid, c.clientname, c.billingdate, 
   (SELECT previousbalance FROM invoice i 
     WHERE i.client = c.clientid ORDER BY i.invoiceid DESC LIMIT 1) AS remaining 
FROM client c 
ORDER BY clientname

See this SQLFiddle

答案 2 :(得分:0)

您拥有的语法将在SQL Server中使用。您的错误消息来自MySQL。

试试这个:

SELECT c.clientid, 
       c.clientname, 
       c.billingdate, 
       (
       SELECT previousbalance 
       FROM invoice i 
       WHERE i.client = c.clientid 
       ORDER BY i.invoiceid DESC
       LIMIT 1  
       ) AS remaining 
FROM client c 
ORDER BY clientname