Programing

MySQL의 테이블 필드에 인덱스가 있는지 어떻게 확인합니까?

lottogame 2020. 8. 23. 09:39
반응형

MySQL의 테이블 필드에 인덱스가 있는지 어떻게 확인합니까?


Google에 몇 번 필요했기 때문에 Q / A를 공유하고 있습니다.


다음 SHOW INDEX과 같이 사용하십시오 .

SHOW INDEX FROM [tablename]

문서 : https://dev.mysql.com/doc/refman/5.0/en/show-index.html


시험:

SELECT * FROM information_schema.statistics 
  WHERE table_schema = [DATABASE NAME] 
    AND table_name = [TABLE NAME] AND column_name = [COLUMN NAME]

인덱스에 주어진 이름을 알 필요없이 특정 열에 어떤 종류의 인덱스가 있는지 알려줍니다. 또한 저장 프로 시저에서도 작동합니다 (인덱스 표시와 반대).


SHOW KEYS FROM  tablename WHERE Key_name='unique key name'

테이블에 고유 키가 있는지 확인할 수 있습니다.


show index from table_name where Column_name='column_name';

다음 문을 사용하십시오. SHOW INDEX FROM your_table

그런 다음 필드의 결과를 확인합니다. row [ "Table"], row [ "Key_name"]

"Key_name"을 올바르게 작성했는지 확인하십시오.


CLI에서 테이블 레이아웃을 살펴 보겠습니다. 당신은 할 것입니다

desc mytable

또는

테이블 mytable 표시


열에 대한 인덱스가 데이터베이스 함수로 존재하는 경우 (여기서는 처음부터 순서대로) 기능이 필요한 경우이 코드를 사용 / 채택 할 수 있습니다. 다중 열 인덱스의 위치에 관계없이 인덱스가 존재하는지 확인하려면 "AND SEQ_IN_INDEX = 1"부분을 삭제하면됩니다.

DELIMITER $$
CREATE FUNCTION `fct_check_if_index_for_column_exists_at_first_place`(
    `IN_SCHEMA` VARCHAR(255),
    `IN_TABLE` VARCHAR(255),
    `IN_COLUMN` VARCHAR(255)
)
RETURNS tinyint(4)
LANGUAGE SQL
DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'Check if index exists at first place in sequence for a given column in a given table in a given schema. Returns -1 if schema does not exist. Returns -2 if table does not exist. Returns -3 if column does not exist. If index exists in first place it returns 1, otherwise 0.'
BEGIN

-- Check if index exists at first place in sequence for a given column in a given table in a given schema. 
-- Returns -1 if schema does not exist. 
-- Returns -2 if table does not exist. 
-- Returns -3 if column does not exist. 
-- If the index exists in first place it returns 1, otherwise 0.
-- Example call: SELECT fct_check_if_index_for_column_exists_at_first_place('schema_name', 'table_name', 'index_name');

-- check if schema exists
SELECT 
    COUNT(*) INTO @COUNT_EXISTS
FROM 
    INFORMATION_SCHEMA.SCHEMATA
WHERE 
    SCHEMA_NAME = IN_SCHEMA
;

IF @COUNT_EXISTS = 0 THEN
    RETURN -1;
END IF;


-- check if table exists
SELECT 
    COUNT(*) INTO @COUNT_EXISTS
FROM 
    INFORMATION_SCHEMA.TABLES
WHERE 
    TABLE_SCHEMA = IN_SCHEMA
AND TABLE_NAME = IN_TABLE
;

IF @COUNT_EXISTS = 0 THEN
    RETURN -2;
END IF;


-- check if column exists
SELECT 
    COUNT(*) INTO @COUNT_EXISTS
FROM 
    INFORMATION_SCHEMA.COLUMNS
WHERE 
    TABLE_SCHEMA = IN_SCHEMA
AND TABLE_NAME = IN_TABLE
AND COLUMN_NAME = IN_COLUMN
;

IF @COUNT_EXISTS = 0 THEN
    RETURN -3;
END IF;

-- check if index exists at first place in sequence
SELECT 
    COUNT(*) INTO @COUNT_EXISTS
FROM 
    information_schema.statistics 
WHERE 
    TABLE_SCHEMA = IN_SCHEMA
AND TABLE_NAME = IN_TABLE AND COLUMN_NAME = IN_COLUMN
AND SEQ_IN_INDEX = 1;


IF @COUNT_EXISTS > 0 THEN
    RETURN 1;
ELSE
    RETURN 0;
END IF;


END$$
DELIMITER ;

다음 SQL 문을 사용하여 테이블의 주어진 열이 인덱싱되었는지 여부를 확인할 수 있습니다.

select  a.table_schema, a.table_name, a.column_name, index_name
from    information_schema.columns a
join    information_schema.tables  b on a.table_schema  = b.table_schema and
                                    a.table_name = b.table_name and 
                                    b.table_type = 'BASE TABLE'
left join (
 select     concat(x.name, '/', y.name) full_path_schema, y.name index_name
 FROM   information_schema.INNODB_SYS_TABLES  as x
 JOIN   information_schema.INNODB_SYS_INDEXES as y on x.TABLE_ID = y.TABLE_ID
 WHERE  x.name = 'your_schema'
 and    y.name = 'your_column') d on concat(a.table_schema, '/', a.table_name, '/', a.column_name) = d.full_path_schema
where   a.table_schema = 'your_schema'
and     a.column_name  = 'your_column'
order by a.table_schema, a.table_name;

조인이 INNODB_SYS_ *에 대해 이루어 지므로 일치 인덱스는 INNODB 테이블에서만 제공됩니다.


인덱스가없는 경우 오류가 발생하므로 특정 show index 쿼리를 실행할 수 없습니다. 따라서 SQL 오류를 방지하려면 모든 인덱스를 배열로 가져 와서 반복해야합니다.

Heres how I do it. I grab all of the indexes from the table (in this case, leads) and then, in a foreach loop, check if the column name (in this case, province) exists or not.

$this->name = 'province';

$stm = $this->db->prepare('show index from `leads`');
$stm->execute();
$res = $stm->fetchAll();
$index_exists = false;

foreach ($res as $r) {
    if ($r['Column_name'] == $this->name) {
        $index_exists = true;
    }
}

This way you can really narrow down the index attributes. Do a print_r of $res in order to see what you can work with.

참고URL : https://stackoverflow.com/questions/127156/how-do-i-check-if-an-index-exists-on-a-table-field-in-mysql

반응형