MS Access SQL - 如何修复联接?

时间:2017-05-09 13:09:39

标签: sql ms-access syntax

我不熟悉MS Access 2003-2007 SQL,但我必须维护/扩展使用它的项目。 (原作者离开了公司.Ho好用于遗留代码。)我想要做的是加入一些相关的表,以便查询给出特定时间范围内特定用户的交易数量。最终的结果是,我希望看到OUT事件与该用户之前的IN事件之间经过了多少小时。

我到目前为止的代码如下:

SELECT Directions.DirectionText, Transactions.Timestamp 
FROM Users 
LEFT JOIN AccessNumbers ON Users.AccessNumberID = AccessNumbers.AccessNumberID 
LEFT JOIN Transactions ON AccessNumbers.Number = Transactions.Number 
LEFT JOIN Events ON Transactions.Event = Events.EventNumber 
LEFT JOIN Readers ON Transactions.ReaderID = Readers.ReaderID 
LEFT JOIN Directions ON Readers.Direction = Direction.Direction 
WHERE 
  (Events.EventNum IN (1, 22)) AND 
  (Users.[Name] = "firstName") AND 
  (Users.Surname = "Surname") AND 
  (Transactions.Timestamp >=#2017-04-10 01:00:00#) AND 
  (Transactions.Timestamp <=#2017-05-09 14:57:30#) 
ORDER BY Transactions.Timestamp

我收到的错误是&#34;语法错误(查询表达式中缺少运算符&#39; Users.AccessNumberID = ... Direction.Direction&#39;

我还尝试了以下方法,以便在JOIN操作中接收&#34;语法错误&#39;:

SELECT Directions.DirectionText, Transactions.Timestamp 
FROM Users 
LEFT JOIN (AccessNumbers ON Users.AccessNumberID = 
AccessNumbers.AccessNumberID)
ON (AccessNumbers.Number = Transactions.Number) 
ON (Transactions.Event = Events.EventNumber) 
ON (Transactions.ReaderID = Readers.ReaderID) 
ON (Readers.Direction = Direction.Direction) 
WHERE ...

我知道SQL需要括号,但我不知道在哪里放置它们。

2 个答案:

答案 0 :(得分:1)

我过去曾试图在我的括号中插入问题...尤其是在使用LEFT连接时。我通常会将您的第一个查询括起来,如下所示:

SELECT Directions.DirectionText, Transactions.Timestamp 
FROM ((((Users 
LEFT JOIN AccessNumbers ON Users.AccessNumberID = AccessNumbers.AccessNumberID) 
LEFT JOIN Transactions ON AccessNumbers.Number = Transactions.Number) 
LEFT JOIN Events ON Transactions.Event = Events.EventNumber) 
LEFT JOIN Readers ON Transactions.ReaderID = Readers.ReaderID) 
LEFT JOIN Directions ON Readers.Direction = Directions.Direction 
WHERE 
  (Events.EventNum IN (1, 22)) AND 
  (Users.[Name] = "firstName") AND 
  (Users.Surname = "Surname") AND 
  (Transactions.Timestamp >=#2017-04-10 01:00:00#) AND 
  (Transactions.Timestamp <=#2017-05-09 14:57:30#) 
ORDER BY Transactions.Timestamp

您的第二个查询需要更多LEFT JOIN个句子才能生效。

答案 1 :(得分:1)

一个简单的技巧如下: 在每个LEFT之前添加一个右括号。 在FROM之后为第一个LEFT之外的每个LEFT添加一个左括号。

结果:

SELECT Directions.DirectionText, Transactions.Timestamp 
FROM ((((Users 
LEFT JOIN AccessNumbers ON Users.AccessNumberID = AccessNumbers.AccessNumberID 
) LEFT JOIN Transactions ON AccessNumbers.Number = Transactions.Number 
) LEFT JOIN Events ON Transactions.Event = Events.EventNumber 
) LEFT JOIN Readers ON Transactions.ReaderID = Readers.ReaderID 
) LEFT JOIN Directions ON Readers.Direction = Direction.Direction 
WHERE 
  (Events.EventNum IN (1, 22)) AND 
  (Users.[Name] = "firstName") AND 
  (Users.Surname = "Surname") AND 
  (Transactions.Timestamp >=#2017-04-10 01:00:00#) AND 
  (Transactions.Timestamp <=#2017-05-09 14:57:30#) 
ORDER BY Transactions.Timestamp

结果与Sturgus说的相同,但是这样添加它们对我来说很有意义。出于布局目的,您可以将每个右括号移动到其上方的行。