检查 table 是否存在的 SQL 语法有什么问题?

What is Wrong with this SQL Syntax that checks if a table exists?

我正在查询服务器并使用 PHP 遍历多个数据库,但出于某种原因,这个 $sql2 查询(我已经阅读过无数线程中的作品)返回语法错误:

$res = mysqli_query($conn,"SHOW DATABASES");

if (!$res){
    // Deal with error
}

while ($d = mysqli_fetch_array($res)){

    $db = $d['Database'];

    $sql1 = "USE $db";
    $query1 = mysqli_query($conn, $sql1);

    if (!$query1){
        // Deal with error
    }

    $sql2 = "IF (EXISTS (SELECT *
                 FROM INFORMATION_SCHEMA.TABLE
                 WHERE TABLE_SCHEMA = '$db'
                 AND TABLE_NAME = 'appusers'))
             BEGIN
                 SELECT * FROM `appusers`
             END";

    $query2 = mysqli_query($conn, $sql2);

    if (!$query2){
        // Deal with error
    }
}

这是我收到的错误:

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 'IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE WHERE TABLE_S' at line 1

我的 MySQL 服务器版本是 5.6.27,我的 PHP 解释器是 5.6

您不能将 IF 语句用作查询,只能在存储过程中使用。您需要执行两个单独的查询。

$sql = "SELECT COUNT(*) AS count
        FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_SCHEMA = '$db'
        AND TABLE_NAME = 'appusers'";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn);
$row = mysqli_fetch_assoc($result);
if ($row['count'] != 0) {
    $sql2 = "SELECT * FROM appusers";
    $query2 = mysqli_query($conn, $sql2);
    ...
} else {
    // deal with error
}

SQL中没有if(尽管mysql有一个function called if

显然,您想 运行 查询 table 是否存在。更常见的方法是尝试 运行ning 查询并检查您收到的错误是否表示 table 不存在。

例如如果您 运行 在 mysql 命令行应用程序中查询,您可能会得到:

mysql> SELECT * FROM appusers;
ERROR 1146 (42S02): Table 'test.appusers' doesn't exist

您看到两个代码:

对于您的情况,检查 SQL 状态可能会更好,因为它涵盖了更多情况。例如,all of these mysql error codes map to SQL state 42S02:

  • 1051 - 未知 table“%s”
  • 1109 - 未知 table“%s”在 %s
  • 1146 - Table“%s.%s”不存在