从同一个表执行两次JOIN时出现SQLite语法错误

时间:2015-08-07 07:21:57

标签: sqlite android-sqlite

我有一个包含4个表的数据库:Task,User,Client和Team。 Task表有几个外键:

  • teamId,一个用于引用Team表中一行的外键
  • authorId,用于引用User表中的行的外键
  • assignedTeamMemberId,用于引用User表中的行的外键
  • clientId,用于引用Client表中的行的外键

查询任务时,我加入了User,Client和Team表。对于引用authorIdassignedMemberId,User表连接两次。这导致了这个查询(为了便于阅读,在子句之间添加了更多的空格):

SELECT 
Task.*, 
Client.uuid AS clientUuid, 
Client.firstName AS clientFirstName, 
Client.lastName AS clientLastName, 
Client.address AS clientAddress, 
authorTable.uuid AS authorUuid, 
authorTable.firstName AS authorFirstName, 
authorTable.lastName AS authorLastName, 
assignedMemberTable.uuid AS assignedTeamMemberUuid, 
assignedMemberTable.firstName AS assignedTeamMemberFirstName, 
assignedMemberTable.lastName AS assignedTeamMemberLastName, 
Team.uuid AS assignedTeamUuid, Team.name AS assignedTeamName 

FROM Task 

JOIN 
Client ON Task.clientId=Client._id 
User as authorTable ON Task.authorId=authorTable._id 
User as assignedMemberTable ON  Task.assignedTeamMemberId=assignedMemberTable._id 
Team ON Task.assignedTeamId=Team._id;

执行时会抛出异常:

android.database.sqlite.SQLiteException: near "User": syntax error (code 1): , while compiling: SELECT Task.*, Client.uuid AS clientUuid, Client.firstName AS clientFirstName, Client.lastName AS clientLastName, Client.address AS clientAddress, authorTable.uuid AS authorUuid, authorTable.firstName AS authorFirstName, authorTable.lastName AS authorLastName, assignedMemberTable.uuid AS assignedTeamMemberUuid, assignedMemberTable.firstName AS assignedTeamMemberFirstName, assignedMemberTable.lastName AS assignedTeamMemberLastName, Team.uuid AS assignedTeamUuid, Team.name AS assignedTeamName FROM Task JOIN Client ON Task.clientId=Client._id User as authorTable ON Task.authorId=authorTable._id User as assignedMemberTable ON Task.assignedTeamMemberId=assignedMemberTable._id Team ON Task.assignedTeamId=Team._id

为什么会抛出语法错误?即使在JOIN子句中使用User as authorTable

1 个答案:

答案 0 :(得分:3)

每个联接必须具有JOIN关键字,例如

FROM a
  JOIN b ON a.id = b.other
  JOIN c ON a.id = c.other

等等。否则,系统不知道您要执行的操作或您想要的连接类型。