In addition, the foreign key must / must refer to the primary key. What if I do not know the primary key, but I know another unique column, in this case the user name, how will I either get the primary key from another MySQL statement, or alternatively, if the foreign key points to a non-primary key?
Yes, if you have another unique key, you can have foreign keys that reference it:
CREATE TABLE user ( userid INT NOT NULL , username VARCHAR(20) NOT NULL
And if all foreign keys in other tables refer to this unique key ( username ), it makes no sense to have a meaningless identifier. You can drop it and make username PRIMARY KEY tables.
(Edit :) There are several points with an automatically increasing primary key for InnoDB tables, even if it is not used as a reference, because the first Primary or Unique index is created by the default clustering index of the table. The primary char field may have performance INSERT for the INSERT and UPDATE , but it is better to execute SELECT .
For a discussion of what to use, a surrogate (meaningless, automatically generated) or natural key and different views on this subject, read this: surrogate-vs-natural-business-keys
source share