MYSQL查询给出了语法错误

时间:2015-08-12 07:36:06

标签: mysql phpmyadmin

我在phpmyadmin上运行此查询,它会出现语法错误,

Delete from users_roles as ur where ur.uid NOT IN (select u.uid from users as u)

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 'as ur where ur.uid NOT IN (select u.uid from users as u)' at line 1 

当我运行此查询时

select ur.uid from users_roles as ur where ur.uid NOT IN (select u.uid from users as u)

它给了我结果。

3 个答案:

答案 0 :(得分:1)

您不能在DELETE语句的那种形式中使用别名。它应该是:

DELETE FROM users_roles 
WHERE uid NOT IN (SELECT uid FROM users)

要使用别名,您必须使用不同的语法:

DELETE ur FROM users_roles AS ur
WHERE ur.uid NOT IN (SELECT uid FROM users)

此语法通常仅在JOIN语句中执行DELETE时使用,因此您需要引用JOIN中的特定表和列。当你只是提到一张桌子时,不需要它。例如,您可以将查询重写为:

DELETE ur
FROM users_roles AS ur
LEFT JOIN users AS u ON ur.uid = u.uid
WHERE u.uid IS NULL

参见MySQL documentationDELETE的第一种形式仅允许 tbl_name ,第二种形式允许 table_references ,后者允许是可以定义别名的地方。

答案 1 :(得分:0)

尝试删除别名:

Delete from users_roles where uid NOT IN (select uid from users)

请参阅SQL Fiddle中的演示。

修改

当您需要使用别名进行删除查询时(使用联接查询时),您可以执行以下操作:

Delete ur from users_roles as ur where ur.uid NOT IN (select u.uid from users as u)

答案 2 :(得分:0)

不要使用别名删除试试这个 从users_roles中删除users_roles.uid NOT IN(从用户那里选择u.uid作为你)