簡體   English   中英

MySQL使用SELECT WHERE主鍵= XYZ

[英]MySQL using SELECT WHERE Primary Key = XYZ

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

示例情況:

table1:
name (P) | surname

table2:
page (P) | content

我試過(PHP)

SELECT * FROM $table WHERE PRIMARY=$row

並且沒有返回任何內容(盡管PHPMyAdmin突出顯示它)。

我想這樣做是因為我想創建一個getDbData函數,我只需要指定表( $table )和行( $row ,行名是主鍵的值),它就可以返回我需要的單行。

我猜你不想提供主鍵的名稱,而是自動選擇它。 在這種情況下,您應首先獲取主鍵的列名,然后將簡單查詢傳遞給主鍵的名稱。

// 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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM