I have a MYSQL database (in PHPMyAdmin) with two tablesusersandposts. Both tables have ausernamecolumn. I want to modify theusernamecolumn in thepoststable so that it extracts the username data from theuserstable, that is, thepoststable The data is automatically updated from theuserstable and is referenced during any updates to theuserstable.
I initially thought I could use foreign keys to achieve this functionality, but if I understand correctly, foreign keys are only associated with the primary key in the parent table, right?
I get an error saying the following syntax is incorrect, although it doesn't give any hints/solutions:
ALTER TABLE posts MODIFY COLUMN username VARCHAR(55) NOT NULL REFERENCES users(username) ON UPDATE CASCADE
How to modify an existing column so that it references/uses data from a column in a different table in the database?
Theusernamecolumns in the two tables have the same type, size and attributes, that is,VARCHAR(55) NOT NULL, and the innoDB storage engine is used.
Foreign keys are a data integrity check, nothing more. It ensures that the fields in the child table contain values that appear in the referenced fields in the parent table. That's it*.
You cannot use foreign keys to merge data from one table into another table. However, the
JOINstatement does exactly what you need, and used with the foreign key ensures that each post has a valid username to identify the correct user data.Take this example:
User data
Post
We can
JOINtheuserdatatable with thepoststable using the following query:You can further create a
VIEWbased on this query to return data:Use the
SELECTstatement to query the view:Demo:https://www.db-fiddle.com/f/tbBXvthBtwH7CKu1yjzPjQ/0
*Foreign keys also allow updates and deletes from the parent table to be cascaded to the child tables, but this is beyond the scope of this article.