SQL 一次创建多个表
我需要一次创建多个表。我很难找出完成此任务的正确方法。目前我的脚本如下所示:
private function buildDB() {
$sql = <<<MySQL_QUERY
CREATE TABLE IF NOT EXISTS headings (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100)
)
CREATE TABLE IF NOT EXISTS titles (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100)
)
MySQL_QUERY;
return mysql_query($sql);
}
显然,这不起作用,并且没有创建表。有没有一种简单的方法可以同时创建多个表?
I need to create multiple tables at once. Im having a hard time figuring out the correct method for accomplishing this. Currently my script looks like this:
private function buildDB() {
$sql = <<<MySQL_QUERY
CREATE TABLE IF NOT EXISTS headings (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100)
)
CREATE TABLE IF NOT EXISTS titles (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100)
)
MySQL_QUERY;
return mysql_query($sql);
}
Obviously, this doesn't work and no tables are created. Is there a simple way for creating multiple tables at once?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
MySQL 变得很困惑,因为你没有分隔查询。在第一个
CREATE
语句后添加一个分号:另外,请确保
MySQL_QUERY
位于行的开头,并且除了分号之外没有其他字符,根据 Heredoc 文档。鉴于上述似乎不起作用,请尝试以下代码:
您可以使用
mysqli_multi_query()
(MySQL版本不存在),但是您'那么就必须使用MySQLi。上面的代码返回两个查询的逻辑 AND,因此如果失败,您仍然会返回0
。MySQL is getting confused because you're not delimiting your queries. Add a semicolon after the first
CREATE
statement:Also, make sure
MySQL_QUERY
is at the beginning of the line with no other characters, except maybe a semicolon, as per the Heredoc documentation.Seeing as the above doesn't appear to work, give this code a try:
You could use
mysqli_multi_query()
(the MySQL version doesn't exist), but you'd have to use MySQLi then. The above code returns the logical AND of the two queries, so you still get a0
returned if one fails.您可以发出多个查询,只要它们被正确分隔即可。当发出多个查询时,将其更改为:
并且
您应该被设置。
如果没有,请进行一些调试,以准确查看您的 SQL 或周围代码不满意的地方。
You can issue multiple queries as long as they are properly delimited. When issuing multiple queries, change this:
to
and you should be set.
If not, throw some debugging in there to see exactly where your SQL or surrounding code is unhappy.
这是因为 mysql_query() 一次只能执行一个查询。请尝试使用 mysqli::multi_query() 代替(http://php.net/manual/en/mysqli.multi-query.php),但请以分号结束查询。
然而,最简单的方法是直接在 MySQL 客户端中运行 CREATE TABLE 语句
It is because mysql_query() can execute only a single query at a time. Please try using mysqli::multi_query() instead (http://php.net/manual/en/mysqli.multi-query.php) but do end your queries with a semi-colon.
The simplest approach however is to directly run the CREATE TABLE statements in your MySQL client