MySQL使用SELECT WHERE主键= XYZ

Kie*_*ran 4 php mysql primary-key where-clause

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

示例情况:

table1:
name (P) | surname

table2:
page (P) | content
Run Code Online (Sandbox Code Playgroud)

我试过(PHP)

SELECT * FROM $table WHERE PRIMARY=$row
Run Code Online (Sandbox Code Playgroud)

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

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

Sto*_*oic 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
Run Code Online (Sandbox Code Playgroud)

$primary通过运行第一个查询获得的列名称在哪里.

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

SHOW KEYS FROM table WHERE Key_name = 'PRIMARY'
// Column_name will contain the name of the primary key.
Run Code Online (Sandbox Code Playgroud)