SQL一次创建多个表 [英] SQL Create multiple tables at once
问题描述
我需要一次创建多个表.我很难找出正确的方法来完成此任务.目前,我的脚本如下所示:
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?
推荐答案
MySQL变得令人困惑,因为您没有界定查询范围.在第一个CREATE
语句之后添加分号:
MySQL is getting confused because you're not delimiting your queries. Add a semicolon after the first CREATE
statement:
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);
}
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:
private function buildDB() {
$sql1 = "CREATE TABLE IF NOT EXISTS headings (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100))";
$sql2 = "CREATE TABLE IF NOT EXISTS titles (
type VARCHAR(150),
heading VARCHAR(100),
uniqueid VARCHAR(100))";
MySQL_QUERY;
return mysql_query($sql1) && mysql_query($sql2);
}
您可以使用mysqli_multi_query()
(MySQL版本不存在),但是那时您必须使用MySQLi.上面的代码返回两个查询的逻辑与,因此,如果一个查询失败,您仍然会得到0
返回.
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 a 0
returned if one fails.
这篇关于SQL一次创建多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!