Compruebe si la tabla existe sin usar " seleccionar de"


¿Hay una manera de comprobar si existe una tabla sin seleccionar y comprobar los valores de la misma?

Es decir, sé que puedo ir SELECT testcol FROM testtable y comprobar el recuento de campos devueltos, pero parece que debe haber una forma más directa / elegante de hacerlo.

 118
Author: Brian Tompsett - 汤莱恩, 2012-01-12

12 answers

No necesitas contar nada.

SELECT 1 FROM testtable LIMIT 1;

Si no hay error, la tabla existe.

O, si quiere ser correcto, use INFORMATION_SCHEMA.

SELECT * 
FROM information_schema.tables
WHERE table_schema = 'yourdb' 
    AND table_name = 'testtable'
LIMIT 1;

Alternativamente, puede usar SHOW TABLES

SHOW TABLES LIKE 'yourtable';

Si hay una fila en el conjunto de resultados, la tabla existe.

 227
Author: Sergio Tulentsev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-12 01:53:01
SELECT count(*)
FROM information_schema.TABLES
WHERE (TABLE_SCHEMA = 'your_db_name') AND (TABLE_NAME = 'name_of_table')

Si obtiene un recuento distinto de cero, la tabla existe.

 51
Author: Marc B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-12 01:45:36

Una comparación de rendimiento:

  • MySQL 5.0.77, en una base de datos que tiene alrededor de 11.000 tablas.
  • Seleccionar una tabla no usada recientemente para que no se almacene en caché.
  • Promediado más de 10 intentos cada uno. (Nota: hecho con diferentes tablas para evitar el almacenamiento en caché).

322ms: show tables like 'table201608';

691ms: select 1 from table201608 limit 1;

319ms: SELECT count(*) FROM information_schema.TABLES WHERE (TABLE_SCHEMA = 'mydb') AND (TABLE_NAME = 'table201608');

Tenga en cuenta que si está ejecutando esto mucho -- como en muchas solicitudes HTML en un corto período de tiempo the el 2do será mucho más rápido ya que se almacenará en caché un promedio 200 ms o más rápido.

 21
Author: Ken Fricklas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-05 00:50:06

Puede consultar la vista del sistema INFORMATION_SCHEMA tables:

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'testtable';

Si no se devuelve ninguna fila, entonces la tabla no existe.

 13
Author: doogle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-12 01:46:11

En lugar de confiar en errores, puede consultar INFORMATION_SCHEMA.TABLES para ver si la tabla existe. Si hay un registro, existe. Si no hay registro, no existe.

 6
Author: ta.speot.is,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-12 01:46:21

Aquí hay una tabla que no es un SELECT * DE

SHOW TABLES FROM `db` LIKE 'tablename'; //zero rows = not exist

Obtuve esto de una base de datos pro, esto es lo que me dijeron:

select 1 from `tablename`; //avoids a function call
select * from IMFORMATION_SCHEMA.tables where schema = 'db' and table = 'table' // slow. Field names not accurate
SHOW TABLES FROM `db` LIKE 'tablename'; //zero rows = not exist
 6
Author: csukcc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-02 13:40:00

Mostrar tablas como 'table_name'

Si esto devuelve filas > 0, la tabla existe

 2
Author: steve,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-16 00:49:59

Solo para agregar una forma adicional de hacerlo, y dependiendo de lo que lo necesite, podría usar un controlador para er_no_such_table error: 1146 como este:

DELIMITER ;;
CREATE PROCEDURE `insert_in_my_table`(in my_var INT)
BEGIN
   -- Error number for table not found
   DECLARE CONTINUE HANDLER FOR 1146
   BEGIN
      -- table doesn't exists, do something...
      CREATE TABLE my_table(n INT);
      INSERT INTO my_table (n) values(my_var);
   END;
      -- table does exists, do something...
      INSERT INTO my_table (n) values(my_var);
END ;;
DELIMITER ;
 1
Author: eracuna,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-19 07:17:16

Puedes hacer algo como a continuación:

            string strCheck = "SHOW TABLES LIKE \'tableName\'";
            cmd = new MySqlCommand(strCheck, connection);
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
            cmd.Prepare();
            var reader = cmd.ExecuteReader();
            if (reader.HasRows)
            {                             
              Console.WriteLine("Table Exist!");
            }
            else
            {                             
              Console.WriteLine("Table does not Exist!");
            }
 1
Author: Manish Jain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-14 10:03:55

Esta solución modificada desde arriba no requiere un conocimiento explícito de la base de datos actual. Entonces es más flexible.

SELECT count(*) FROM information_schema.TABLES WHERE TABLE_NAME = 'yourtable' 
AND TABLE_SCHEMA in (SELECT DATABASE());
 1
Author: Martin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-17 15:17:23

Uso esto en php.

private static function ifTableExists(string $database, string $table): bool
    {
        $query = DB::select("
            SELECT 
                IF( EXISTS 
                    (SELECT * FROM information_schema.COLUMNS
                        WHERE TABLE_SCHEMA = '$database'
                        AND TABLE_NAME = '$table'
                        LIMIT 1),
                1, 0)
                AS if_exists
        ");

        return $query[0]->if_exists == 1;
    }
 0
Author: Raza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-02 19:03:31

Ninguna de las opciones excepto SELECT no permite el nombre de la base de datos como se usa en SELECT, así que escribí esto:

SELECT COUNT(*) AS cnt FROM information_schema.TABLES 
WHERE CONCAT(table_schema,".",table_name)="db_name.table_name";
 -1
Author: Atis Lezdins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-06 11:53:34