MySQL:动态确定表的主键 [英] MySQL: Determine Table's Primary Key Dynamically

查看:82
本文介绍了MySQL:动态确定表的主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用PHP生成这样的SQL查询:

I'm, generating a SQL query like this in PHP:

$sql = sprintf("UPDATE %s SET %s = %s WHERE %s = %s", ...);

由于该查询的几乎每个部分都是动态的,因此我需要一种动态确定表主键的方法,这样我就可以进行如下查询:

Since almost every part of this query is dynamic I need a way to determine the table's primary key dynamically, so that I'd have a query like this:

$sql = sprintf("UPDATE %s SET %s=%s WHERE PRIMARY_KEY = %s", ...);

表的主键是否有MySQL关键字,或者是获取表的主键的方法?

Is there a MySQL keyword for a table's primary key, or a way to get it?

我以前曾使用过information_schema数据库来查找类似的信息,但是如果我不必求助于此,那将是很好的选择.

I've used the information_schema DB before to find information like this, but it'd be nice if I didn't have to resort to that.

推荐答案

SHOW INDEX FROM <tablename>

您想要其中Key_name = PRIMARY的行

You want the row where Key_name = PRIMARY

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

您可能想要缓存结果-在您可能需要使用的所有表上运行SHOW语句需要花费一些时间.

You'll probably want to cache the results -- it takes a while to run SHOW statements on all the tables you might need to work with.

这篇关于MySQL:动态确定表的主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆