MySQL使用SELECT WHERE主键= XYZ

时间:2013-12-07 22:15:48

标签: php mysql primary-key where-clause

是否可以在MySQL的SELECT * WHERE查询中使用“主键”而不是列?

示例情况:

table1:
name (P) | surname

table2:
page (P) | content

我试过(PHP)

SELECT * FROM $table WHERE PRIMARY=$row

并且没有返回任何内容(尽管PHPMyAdmin突出显示它)。

我想这样做,因为我想创建一个getDbData函数,我只需要指定表($table)和行($row,行名是主键值)它返回我需要的单行。

1 个答案:

答案 0 :(得分:6)

我猜您不想提供主键的名称,而是自动选择它。在这种情况下,您应首先获取主键的列名,然后将简单查询传递给主键的名称。

// first query
SELECT k.column_name
FROM information_schema.table_constraints t
JOIN information_schema.key_column_usage k
USING(constraint_name,table_schema,table_name)
WHERE t.constraint_type='PRIMARY KEY'
  AND t.table_schema='YourDatabase'
  AND t.table_name='YourTable';

// second query
SELECT * FROM $table WHERE $primary=$row

其中$primary是您通过运行第一个查询获得的列名。

更好的方法是使用SHOW KEYS,因为您并不总是可以访问information_schema。以下作品:

SHOW KEYS FROM table WHERE Key_name = 'PRIMARY'
// Column_name will contain the name of the primary key.
相关问题