SQL一次创建多个表 [英] SQL Create multiple tables at once

查看:2190
本文介绍了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?

推荐答案

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);
}

此外,根据MySQL_QUERY位于该行的开头,并且除分号外,没有其他字符. net/manual/zh-CN/language.types.string.php#language.types.string.syntax.heredoc"rel =" nofollow>此处的文档.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆