我有一个包含4个表的数据库:Task,User,Client和Team。 Task表有几个外键:
teamId
,一个用于引用Team表中一行的外键authorId
,用于引用User表中的行的外键assignedTeamMemberId
,用于引用User表中的行的外键clientId
,用于引用Client表中的行的外键查询任务时,我加入了User,Client和Team表。对于引用authorId
和assignedMemberId
,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
?
答案 0 :(得分:3)
每个联接必须具有JOIN关键字,例如
FROM a
JOIN b ON a.id = b.other
JOIN c ON a.id = c.other
等等。否则,系统不知道您要执行的操作或您想要的连接类型。