Pregunta

He necesitado buscar esto en Google un par de veces, así que comparto mis preguntas y respuestas.

¿Fue útil?

Solución

Usar SHOW INDEX al igual que:

SHOW INDEX FROM [tablename]

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

Otros consejos

Intentar:

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

Le dirá si hay un índice de algún tipo en una determinada columna sin necesidad de saber el nombre dado al índice.También funcionará en un procedimiento almacenado (a diferencia de mostrar índice)

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

Puedes encontrar si existe una clave única en la tabla.

show index from table_name where Column_name='column_name';

Utilice la siguiente declaración:MOSTRAR ÍNDICE DE tu mesa

Y luego verifique el resultado de los campos:fila["Tabla"], fila["nombre_clave"]

Asegúrate de escribir "Key_name" correctamente

simplemente mirar el diseño de las tablas desde el cli.tu harías

desc mi tabla

o

mostrar tabla mytable

Si necesita la funcionalidad si existe un índice para una columna (aquí en primer lugar en secuencia) como función de base de datos, puede usar/adoptar este código.Si desea comprobar si existe un índice independientemente de la posición en un índice de varias columnas, simplemente elimine la parte "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 ;

puede utilizar la siguiente declaración SQL para verificar que la columna dada en la tabla esté indexada o no

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;

dado que las uniones son contra INNODB_SYS_*, los índices de coincidencia solo provienen de tablas INNODB

No puede ejecutar una consulta de índice de presentación específica porque generará un error si no existe un índice.Por lo tanto, debe tomar todos los índices en una matriz y recorrerlos si desea evitar errores de SQL.

Así es como lo hago.Tomo todos los índices de la tabla (en este caso, leads) y luego, en un bucle foreach, verifique si el nombre de la columna (en este caso, province) existe o no.

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

De esta manera realmente puedes limitar los atributos del índice.hacer un print_r de $res para ver con qué puedes trabajar.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top