MySQL: Determine Table's Primary Key Dynamically

前端 未结 5 2114
别那么骄傲
别那么骄傲 2020-12-03 14:06

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 thi

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 14:28

    It might be not advised but works just fine:

    SHOW INDEX FROM  WHERE Key_name = 'PRIMARY';
    

    The solid way is to use information_schema:

    SELECT k.COLUMN_NAME
    FROM information_schema.table_constraints t
    LEFT JOIN information_schema.key_column_usage k
    USING(constraint_name,table_schema,table_name)
    WHERE t.constraint_type='PRIMARY KEY'
        AND t.table_schema=DATABASE()
        AND t.table_name='owalog';
    

    As presented on the mysql-list. However its a few times slower from the first solution.

提交回复
热议问题