如何获取mysql数据库中某个表的主键或唯一字段
求一条SQL语句,获取mysql数据库中表table中主键字段的名称,如果没有主键,则返回一个唯一字段名称例如数据结构:id(主键),name(..)...那么返回结果应...
求一条SQL语句,获取mysql数据库中表table中主键字段的名称,
如果没有主键,则返回一个唯一字段名称
例如数据结构:id(主键),name(..)...那么返回结果应该是id
$con=new mysqli('localhost','root','','dbname');
$sql=....???//
$con->query($sql); 展开
如果没有主键,则返回一个唯一字段名称
例如数据结构:id(主键),name(..)...那么返回结果应该是id
$con=new mysqli('localhost','root','','dbname');
$sql=....???//
$con->query($sql); 展开
2个回答
展开全部
describe 表名 ;
然后循环取字段名和属性,判断哪个是主键 Key=='PRI'为主键
mysql> describe cdb_videos;
+--------------+-----------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-----------------------+------+-----+---------+-------+
| vid | varchar(16) | NO | PRI | | |
| uid | mediumint(8) unsigned | NO | | 0 | |
| dateline | int(10) unsigned | NO | MUL | 0 | |
| displayorder | tinyint(3) | NO | MUL | 0 | |
| tid | mediumint(8) unsigned | NO | | 0 | |
| pid | int(10) unsigned | NO | | 0 | |
| vtype | tinyint(1) unsigned | NO | | 0 | |
| vview | mediumint(8) unsigned | NO | | 0 | |
| vtime | smallint(6) unsigned | NO | | 0 | |
| visup | tinyint(1) unsigned | NO | | 0 | |
| vthumb | varchar(128) | NO | | | |
| vtitle | varchar(64) | NO | | | |
| vclass | varchar(32) | NO | | | |
| vautoplay | tinyint(1) | NO | | 0 | |
+--------------+-----------------------+------+-----+---------+-------+
然后循环取字段名和属性,判断哪个是主键 Key=='PRI'为主键
mysql> describe cdb_videos;
+--------------+-----------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-----------------------+------+-----+---------+-------+
| vid | varchar(16) | NO | PRI | | |
| uid | mediumint(8) unsigned | NO | | 0 | |
| dateline | int(10) unsigned | NO | MUL | 0 | |
| displayorder | tinyint(3) | NO | MUL | 0 | |
| tid | mediumint(8) unsigned | NO | | 0 | |
| pid | int(10) unsigned | NO | | 0 | |
| vtype | tinyint(1) unsigned | NO | | 0 | |
| vview | mediumint(8) unsigned | NO | | 0 | |
| vtime | smallint(6) unsigned | NO | | 0 | |
| visup | tinyint(1) unsigned | NO | | 0 | |
| vthumb | varchar(128) | NO | | | |
| vtitle | varchar(64) | NO | | | |
| vclass | varchar(32) | NO | | | |
| vautoplay | tinyint(1) | NO | | 0 | |
+--------------+-----------------------+------+-----+---------+-------+
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询