mysql 检查表列名是否存,如何检查MySQL中的表字段上是否存在索引?

像这样使用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]

它会告诉你,如果某一列上有任何types的索引,而不需要知道索引的名字。 它也将工作在一个存储过程(而不是显示索引)

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

你可以find表中是否存在一个唯一的键

show index from table_name where Column_name='column_name';

只是从cli中查看表格布局。 你会做的

desc mytable

要么

显示表mytable

您可以使用以下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表

您不能运行特定的显示索引查询,因为如果索引不存在,它将引发错误。 因此,如果要避免任何SQL错误,则必须将所有索引都抓取到数组中并进行循环。

下面是我如何做到这一点。 我抓取表中的所有索引(在这个例子中是lead),然后在foreach循环中检查列名是否存在(在本例中是province )。

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

这样可以真正缩小索引属性的范围。 做一个$res的print_r为了看看你可以使用什么。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值