So I understand how to create foreign keys and I know what is the purpose of the FK. But I have a problem in understanding How to use them. I asked a question regarding Fore
Instead of reading so many links, just try to implement this in any simple project. I'm just explaining how we gonna use the above tables.
Suppose you 3 users in user
table and 5 items in items
table.
user
table
id | username | password
1 abc 123
2 def 456
3 qwe 987
items
table
i_id | name | price
1 item 1 6
2 item 2 8
3 item 3 11
4 item 4 3
5 item 5 14
your user_purchase
table look like this
CREATE TABLE user_purchase( i_id INT(11) NOT NULL, id INT(11) NOT NULL, FOREIGN KEY (i_id) REFERENCES items(i_id), FOREIGN KEY (id) REFERENCES user(id) );
There is no need of item name again in this table. So I have removed.
i_id | id
1 1
1 2
2 2
3 3
In the above table we will get, user 1 has purchased item 1, user 2 has purchased item 1,item 2 and user 3 has purchased item 3.
This is how normalization works. You can use MySQL JOIN for getting user name and item details
SELECT B.user_name,C.name AS item_name,C.price
FROM user_purchase A
JOIN user B ON A.id = B.id
JOIN items C ON A.i_id = C.i_id
Here is foreign key use to join
A.id = B.id
A.i_id = C.i_id