How to use foreign keys with PHP

前端 未结 5 1525
无人及你
无人及你 2021-01-05 08:51

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

5条回答
  •  南笙
    南笙 (楼主)
    2021-01-05 09:36

    Foreign keys are used in joins. For instance, if you want to know the usernames that purchased a particular item, you would write:

    select u.username
    from items i
    join user_purchase up on i.i_id = up.i_id
    join user u on u.id = up.id
    where i.name = "Some product name"
    

    They may also be used by the database engine itself. It can detect if you create a row in user_purchase whose id or i_id column doesn't match anything in the referenced column in the other table.

    You should not replicate the name column in the user_purchase table. The name is just an attribute of the item, it's not specific to any particular purchase. If you need to get the name of the item that was purchased, join with the items table.

提交回复
热议问题