我想了解MYSQL 是如何确定单表和多表语法的,但我找不到这些信息。 documentation解释了 MYSQL 如何处理这两者,但没有解释是什么决定了它们。
文档说:
You can specify multiple tables in a DELETE statement to delete rows from one or more tables depending on the particular condition in the WHERE clause. However, you cannot use ORDER BY or LIMIT in a multiple-table DELETE.
以这个查询为例:
DELETE table FROM table
INNER JOIN other ON other.column = table.column
WHERE other.column2 = ?
LIMIT 1
这是单表语法还是多表语法?有一个 JOIN
,因此您可以倾向于多个,但它只是从一个表中删除。我的另一个怀疑是,它是在多个 WHERE
子句用于多个表时确定的。如果您能在回答中包含这两个示例,我们将不胜感激!
编辑:
我问这个问题是因为当使用 LIMIT
执行某些 DELETE
查询时,我得到一个错误,您不能将 LIMIT
与多表语法一起使用.
编辑#2:
简而言之,如果要在 DELETE
查询中联接表,则不能使用 ORDER BY
或 LIMIT
。
最佳答案
MySQL's documentation states the following
关于“单表”语法:
If the ORDER BY clause is specified, the rows are deleted in the order that is specified. The LIMIT clause places a limit on the number of rows that can be deleted.
关于“多表”语法:
For the multiple-table syntax, DELETE deletes from each tbl_name the rows that satisfy the conditions. In this case, ORDER BY and LIMIT cannot be used.
一些测试揭示了 ORDER BY
的局限性。
这是一个有效的单表 DELETE
语句,带有 ORDER BY
:
DELETE FROM table
WHERE somecol = 'someval'
ORDER BY timestamp LIMIT 2
对另一个表进行显式连接条件的类似查询会导致 ORDER BY
语法错误,尽管只有一个表被删除:
DELETE table1
FROM table1 JOIN table2 ON table1.id = table2.id
WHERE somecol = 'someval'
ORDER BY timestamp LIMIT 2
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ORDER BY timestamp LIMIT 2' at line 1
用隐式连接指定相同的查询以同样的方式失败
DELETE table1
FROM table1, table2
WHERE
table1.id = table2.id
AND somecol = 'someval'
ORDER BY timestamp LIMIT 2
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ORDER BY timestamp LIMIT 2' at line 1
在连接(多表)语句中,在 DELETE
之后没有指定表用于删除,因此它看起来更像是单表语法也是语法错误
DELETE /* no table named here */
FROM table1 JOIN table2 ON table1.id = table2.id
WHERE somecol = 'someval'
ORDER BY timestamp LIMIT 2
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE somecol
它是在DELETE
子句中命名的表:
最后,只使用一个表,但使用多表语法(在 DELETE
关键字后命名表)不允许 ORDER BY
,所以这里真正的识别区别似乎是在 DELETE
子句中命名的表,以区分多表和单表:
此查询仅涉及一个表(没有连接),但会产生语法错误:
/* name table1 in the DELETE clause */
DELETE table1
/* but not other table is joined */
FROM table1
WHERE somecol = 'someval'
ORDER BY id LIMIT 2
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ORDER BY id LIMIT 1
关于mysql - 单表和多表语法的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28004962/