1

I am getting a syntax error can anybody tell me why?

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

What the secondary select is doing is getting the latest record for that clientid in the invoice table.

The program - HediSQl

SQL

And here is the error:

SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1 previousbalance FROM invoice i WHERE i.client = c.clientid ORDER BY i.invoicei' at line 1 */

2
  • 1
    Please show the syntax error here. and which SQL (MySQL, SQL Server etc)? Commented Aug 29, 2012 at 5:24
  • HediSQL is the program, SQL and here is the error SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1 previousbalance FROM invoice i WHERE i.client = c.clientid ORDER BY i.invoicei' at line 1 */ Commented Aug 29, 2012 at 5:29

3 Answers 3

3

Just guessing but it might indicate that you should replace TOP 1 with LIMIT 1 or WHERE ROWNUM < 2 LIMIT 1. What kind of DB are you using?

Sign up to request clarification or add additional context in comments.

2 Comments

This does not work? 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
This should also work: SELECT c.clientid, c.clientname, c.billingdate, remaining.previousbalance FROM client c LEFT JOIN (SELECT i.client, previousbalance FROM invoice i GROUP BY i.client HAVING MAX(invoiceid)) remaining ON c.clientid = remaining.client ORDER BY c.clientname. I also set up an SQLFiddle: sqlfiddle.com/#!2/29e80/10
1

You just need to use LIMIT instead TOP like this:

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

Comments

0

The syntax you have will work in SQL Server. Your error message is from MySQL.

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.