Programming

“select from”을 사용하지 않고 테이블이 존재하는지 확인

procodes 2020. 6. 9. 22:36
반응형

“select from”을 사용하지 않고 테이블이 존재하는지 확인


테이블 에서 값을 선택하고 확인 하지 않고 테이블이 존재하는지 확인하는 방법 이 있습니까?

즉, SELECT testcol FROM testtable돌아가서 반환되는 필드 수를 확인할 수는 있지만 더 직접적이고 우아한 방법이 있어야합니다.


아무 것도 세지 않아도됩니다.

SELECT 1 FROM testtable LIMIT 1;

오류가 없으면 테이블이 존재합니다.

또는 올바르게하려면 INFORMATION_SCHEMA를 사용하십시오 .

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

또는 사용할 수 있습니다 SHOW TABLES

SHOW TABLES LIKE 'yourtable';

결과 집합에 행이 있으면 테이블이 존재합니다.


SELECT count(*)
FROM information_schema.TABLES
WHERE (TABLE_SCHEMA = 'your_db_name') AND (TABLE_NAME = 'name_of_table')

0이 아닌 수를 얻으면 테이블이 존재합니다.


성능 비교 :

  • 약 11,000 개의 테이블이있는 DB의 MySQL 5.0.77
  • 캐시되지 않도록 최근에 사용하지 않은 테이블을 선택합니다.
  • 시도당 평균 10 회 이상 (참고 : 캐싱을 피하기 위해 다른 테이블로 수행됨).

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

단기간에 많은 HTML 요청과 같이이 작업을 많이 수행하면 평균 200ms 이상으로 캐시되므로 두 번째는 훨씬 빠릅니다.


INFORMATION_SCHEMA tables시스템 뷰를 쿼리 할 수 ​​있습니다 .

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

행이 반환되지 않으면 테이블이 존재하지 않는 것입니다.


오류에 의존하는 대신 INFORMATION_SCHEMA.TABLES테이블이 존재하는지 쿼리 할 수 있습니다. 레코드가 있으면 존재합니다. 레코드가 없으면 존재하지 않습니다.


다음은 SELECT * FROM이 아닌 테이블입니다.

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

데이터베이스 전문가로부터 이것을 얻었습니다. 내가 들었던 것은 다음과 같습니다.

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

위의 내용을 모두 읽은 후 다음 진술을 선호합니다.

SELECT EXISTS(
       SELECT * FROM information_schema.tables 
       WHERE table_schema = 'db' 
       AND table_name = 'table'
);

그것은 당신이하고 싶은 것을 정확하게 나타내고 실제로 '부울'을 반환합니다.


위에서 수정 한 솔루션에는 현재 데이터베이스에 대한 명시적인 지식이 필요하지 않습니다. 그런 다음 더 유연합니다.

SELECT count(*) FROM information_schema.TABLES WHERE TABLE_NAME = 'yourtable' 
AND TABLE_SCHEMA in (SELECT DATABASE());

추가 방법을 추가하기 위해 필요한 방법에 따라 er_no_such_table error : 1146에 대한 핸들러다음과 같이 사용할 수 있습니다 .

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 ;

'table_name'과 같은 테이블 표시

이것이 행> 0을 반환하면 테이블이 존재합니다


아래와 같이 할 수 있습니다 :

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

나는 이것을 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;
    }

답변을 확장하면 테이블이 존재하는지 여부에 따라 TRUE / FALSE를 반환하는 함수를 추가로 작성할 수 있습니다.

CREATE FUNCTION fn_table_exists(dbName VARCHAR(255), tableName VARCHAR(255))
  RETURNS BOOLEAN
  BEGIN
    DECLARE totalTablesCount INT DEFAULT (
      SELECT COUNT(*)
      FROM information_schema.TABLES
      WHERE (TABLE_SCHEMA COLLATE utf8_general_ci = dbName COLLATE utf8_general_ci)
        AND (TABLE_NAME COLLATE utf8_general_ci = tableName COLLATE utf8_general_ci)
    );
    RETURN IF(
      totalTablesCount > 0,
      TRUE,
      FALSE
    );
END
;


SELECT fn_table_exists('development', 'user');

여기에 대한 답변과 관련하여 몇 가지 문제가 있습니다.

1) TEMPORARY 테이블을 포함 INFORMATION_SCHEMA.TABLES하지 않습니다 .

2) Using any type of SHOW query, i.e. SHOW TABLES LIKE 'test_table', will force the return of a resultset to the client, which is undesired behavior for checking if a table exists server-side, from within a stored procedure that also returns a resultset.

3) As some users mentioned, you have to be careful with how you use SELECT 1 FROM test_table LIMIT 1.

If you do something like:

SET @table_exists = 0;
SET @table_exists = (SELECT 1 FROM test_table LIMIT 1);

You will not get the expected result if the table has zero rows.

Below is a stored procedure that will work for all tables (even TEMPORARY).

It can be used like:

SET @test_table = 'test_table';
SET @test_db = NULL;
SET @does_table_exist = NULL;

CALL DoesTableExist(@test_table, @test_db, @does_table_exist);

SELECT @does_table_exist;

The code:

/*
    p_table_name is required
    p_database_name is optional
        if NULL is given for p_database_name, then it defaults to the currently selected database
    p_does_table_exist
        The @variable to save the result to

    This procedure attempts to
        SELECT NULL FROM `p_database_name`.`p_table_name` LIMIT 0;

    If [SQLSTATE '42S02'] is raised, then
        SET p_does_table_exist = 0
    Else
        SET p_does_table_exist = 1

    Info on SQLSTATE '42S02' at:
        https://dev.mysql.com/doc/refman/5.7/en/server-error-reference.html#error_er_no_such_table
*/

DELIMITER $$

DROP PROCEDURE IF EXISTS DoesTableExist
$$

CREATE PROCEDURE         DoesTableExist (
    IN p_table_name VARCHAR(64),
    IN p_database_name VARCHAR(64),
    OUT p_does_table_exist TINYINT(1) UNSIGNED
)
BEGIN
    /* 793441 is used in this procedure for ensuring that user variables have unique names */

    DECLARE EXIT HANDLER FOR SQLSTATE '42S02'
    BEGIN
        SET p_does_table_exist = 0
        ;
    END
    ;


    IF p_table_name IS NULL THEN
        SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'DoesTableExist received NULL for p_table_name.';
    END IF;


    /* redirect resultset to a dummy variable */

    SET @test_select_sql_793441 = CONCAT(
        "SET @dummy_var_793441 = ("
            " SELECT"
                " NULL"
            " FROM ",
                IF(
                    p_database_name IS NULL,
                    "",
                    CONCAT(
                        "`",
                        REPLACE(p_database_name, "`", "``"),
                        "`."
                    )
                ),
                "`",
                REPLACE(p_table_name, "`", "``"),
                "`"
            " LIMIT 0"
        ")"
    )
    ;

    PREPARE _sql_statement FROM @test_select_sql_793441
    ;
    SET @test_select_sql_793441 = NULL
    ;
    EXECUTE _sql_statement
    ;
    DEALLOCATE PREPARE _sql_statement
    ;

    SET p_does_table_exist = 1
    ;
END
$$

DELIMITER ;

None of the options except SELECT doesn't allow database name as used in SELECT, so I wrote this:

SELECT COUNT(*) AS cnt FROM information_schema.TABLES 
WHERE CONCAT(table_schema,".",table_name)="db_name.table_name";

참고URL : https://stackoverflow.com/questions/8829102/check-if-table-exists-without-using-select-from

반응형