mysql - una - Mostrar restricciones en el comando de tablas
mostrar tablas en mysql workbench (8)
Tengo tablas en las que he intentado establecer relaciones PK FK pero quiero verificar esto. ¿Cómo puedo mostrar las restricciones PK / FK? Vi this página de manual, pero no muestra ejemplos y mi búsqueda en Google tampoco fue rentable. Mi base de datos es credentialing1 y mis tablas restringidas son prácticas y cred_insurances.
Análogamente a @Resh32 , pero sin la necesidad de usar la declaración USE
:
SELECT TABLE_NAME,
COLUMN_NAME,
CONSTRAINT_NAME,
REFERENCED_TABLE_NAME,
REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = "database_name"
AND TABLE_NAME = "table_name"
AND REFERENCED_COLUMN_NAME IS NOT NULL;
Útil, por ejemplo, usando el ORM.
El principal problema con la respuesta validada es que tendrá que analizar el resultado para obtener la información. Aquí hay una consulta que le permite obtenerlos de una manera más útil:
SELECT cols.TABLE_NAME, cols.COLUMN_NAME, cols.ORDINAL_POSITION,
cols.COLUMN_DEFAULT, cols.IS_NULLABLE, cols.DATA_TYPE,
cols.CHARACTER_MAXIMUM_LENGTH, cols.CHARACTER_OCTET_LENGTH,
cols.NUMERIC_PRECISION, cols.NUMERIC_SCALE,
cols.COLUMN_TYPE, cols.COLUMN_KEY, cols.EXTRA,
cols.COLUMN_COMMENT, refs.REFERENCED_TABLE_NAME, refs.REFERENCED_COLUMN_NAME,
cRefs.UPDATE_RULE, cRefs.DELETE_RULE,
links.TABLE_NAME, links.COLUMN_NAME,
cLinks.UPDATE_RULE, cLinks.DELETE_RULE
FROM INFORMATION_SCHEMA.`COLUMNS` as cols
LEFT JOIN INFORMATION_SCHEMA.`KEY_COLUMN_USAGE` AS refs
ON refs.TABLE_SCHEMA=cols.TABLE_SCHEMA
AND refs.REFERENCED_TABLE_SCHEMA=cols.TABLE_SCHEMA
AND refs.TABLE_NAME=cols.TABLE_NAME
AND refs.COLUMN_NAME=cols.COLUMN_NAME
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS cRefs
ON cRefs.CONSTRAINT_SCHEMA=cols.TABLE_SCHEMA
AND cRefs.CONSTRAINT_NAME=refs.CONSTRAINT_NAME
LEFT JOIN INFORMATION_SCHEMA.`KEY_COLUMN_USAGE` AS links
ON links.TABLE_SCHEMA=cols.TABLE_SCHEMA
AND links.REFERENCED_TABLE_SCHEMA=cols.TABLE_SCHEMA
AND links.REFERENCED_TABLE_NAME=cols.TABLE_NAME
AND links.REFERENCED_COLUMN_NAME=cols.COLUMN_NAME
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS cLinks
ON cLinks.CONSTRAINT_SCHEMA=cols.TABLE_SCHEMA
AND cLinks.CONSTRAINT_NAME=links.CONSTRAINT_NAME
WHERE cols.TABLE_SCHEMA=DATABASE()
AND cols.TABLE_NAME="table"
Puedes usar esto:
select
table_name,column_name,referenced_table_name,referenced_column_name
from
information_schema.key_column_usage
where
referenced_table_name is not null
and table_schema = ''my_database''
and table_name = ''my_table''
O para una salida mejor formateada, use esto:
select
concat(table_name, ''.'', column_name) as ''foreign key'',
concat(referenced_table_name, ''.'', referenced_column_name) as ''references''
from
information_schema.key_column_usage
where
referenced_table_name is not null
and table_schema = ''my_database''
and table_name = ''my_table''
Simplemente consulte el INFORMATION_SCHEMA:
USE INFORMATION_SCHEMA;
SELECT TABLE_NAME,
COLUMN_NAME,
CONSTRAINT_NAME,
REFERENCED_TABLE_NAME,
REFERENCED_COLUMN_NAME
FROM KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = "<your_database_name>"
AND TABLE_NAME = "<your_table_name>"
AND REFERENCED_COLUMN_NAME IS NOT NULL;
También hay una herramienta que mysqlshow llamada mysqlshow
Si lo ejecuta con la --k keys $table_name
, mostrará las claves.
SYNOPSIS
mysqlshow [options] [db_name [tbl_name [col_name]]]
.......
.......
.......
· --keys, -k
Show table indexes.
ejemplo:
╰─➤ mysqlshow -h 127.0.0.1 -u root -p --keys database tokens
Database: database Table: tokens
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| id | int(10) unsigned | | NO | PRI | | auto_increment | select,insert,update,references | |
| token | text | utf8mb4_unicode_ci | NO | | | | select,insert,update,references | |
| user_id | int(10) unsigned | | NO | MUL | | | select,insert,update,references | |
| expires_in | datetime | | YES | | | | select,insert,update,references | |
| created_at | timestamp | | YES | | | | select,insert,update,references | |
| updated_at | timestamp | | YES | | | | select,insert,update,references | |
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| tokens | 0 | PRIMARY | 1 | id | A | 2 | | | | BTREE | | |
| tokens | 1 | tokens_user_id_foreign | 1 | user_id | A | 2 | | | | BTREE | | |
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
Trata de hacerlo:
SHOW TABLE STATUS FROM credentialing1;
Las restricciones de clave externa se enumeran en la columna Comentario de la salida.
afaik para hacer una solicitud a information_schema
usted necesita privilegios. Si necesita una lista simple de claves, puede usar este comando:
SHOW INDEXES IN <tablename>
yo suelo
SHOW CREATE TABLE mytable;
Esto le muestra la declaración SQL necesaria para recetar mytable
en su forma actual. Puede ver todas las columnas y sus tipos (como DESC
) pero también muestra información de restricciones (y tipo de tabla, juego de caracteres, etc.).