0

I'm having some trouble trying to get Microsoft Access 2007 to accept my SQL query but it keeps throwing syntax errors at me that don't help me correct the problem.

I have two tables, let's call them Customers and Orders for ease.

I need some customer details, but also a few details from the most recent order. I currently have a query like this:

SELECT c.ID, c.Name, c.Address, o.ID, o.Date, o.TotalPrice
FROM Customers c
INNER JOIN Orders o
ON c.ID = o.CustomerID
AND o.ID = (SELECT TOP 1 ID FROM Orders WHERE CustomerID = c.ID ORDER BY Date DESC)

To me, it appears valid, but Access keeps throwing 'syntax error's at me and when I hit OK, it selects a piece of the SQL text that doesn't even relate to it.

If I take the extra SELECT clause out it works but is obviously not what I need.

Any ideas?

Nick Bedford
  • 4,365
  • 30
  • 36
  • 2
    cmon dude, what are the " 'syntax error's " ?? (not my downvote, BTW) – Mitch Wheat Sep 02 '11 at 04:34
  • It seems like `CustomerID` in your subquery might be ambiguous. But, I'm not sure. – Josh Darnell Sep 02 '11 at 04:37
  • 2
    Mitch, this is **Microsoft** Access. It doesn't have to tell you the cause of the error! It's literally, "Syntax error in your query" and that's it. – Nick Bedford Sep 02 '11 at 04:43
  • Ick, I've seen that before. Then highlights something random. Thanks alot Access. – Josh Darnell Sep 02 '11 at 04:44
  • 1
    Believe me, I'd be using SQL Server if I could. P.S. *Syntax error in query expression ''.* to be exact. – Nick Bedford Sep 02 '11 at 04:48
  • But if you run it in the Access query grid, it will highlight the part of the SQL that is throwing the error. It doesn't do a very good job, as it highlights the first thing it doesn't understand, but it will very often at least tell you which clause the error is in (i.e., SELECT, FROM or WHERE). – David-W-Fenton Sep 03 '11 at 21:11

2 Answers2

1

You cannot use AND in that way in MS Access, change it to WHERE. In addition, you have two reserved words in your column (field) names - Name, Date. These should be enclosed in square brackets when not prefixed by a table name or alias, or better, renamed.

SELECT c.ID, c.Name, c.Address, o.ID, o.Date, o.TotalPrice
FROM Customers c
INNER JOIN Orders o
ON c.ID = o.CustomerID
WHERE o.ID = (
     SELECT TOP 1 ID FROM Orders 
     WHERE CustomerID = c.ID ORDER BY [Date] DESC)
Fionnuala
  • 90,370
  • 7
  • 114
  • 152
0

I worked out how to do it in Microsoft Access. You INNER JOIN on a pre-sorted sub-query. That way you don't have to do multiple ON conditions which aren't supported.

SELECT c.ID, c.Name, c.Address, o.OrderNo, o.OrderDate, o.TotalPrice
FROM Customers c
INNER JOIN (SELECT * FROM Orders ORDER BY OrderDate DESC) o
ON c.ID = o.CustomerID

How efficient this is another story, but it works...

Nick Bedford
  • 4,365
  • 30
  • 36