I'm working on a small pizza delivery website and I ran in to a small problem with the MySQL tables.
I found this on Stackoverflow: https://stackoverflow.com/a/10322293/80907
It mentions the following:
- Both tables have to use the INNODB engine.
- "In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. "
The first isn't really a problem, but the second rule is where I'm scratching my head.
This is a website where you can order pizzas, so I'm saving all data on the users and their order in the database.
Here's a screenshot of what I'm about to write out:
So I'll have a "Users" table and an "Orders" table. The Users will have to have a one-to-many relationship to Orders. Simply put, the order is identified by the user who created it. So it's one-to-many, identifying.
This means that the "Orders" table will have a foreign key, such as "Users_id".
The problem arises when you have to make a table for the many-to-many relationship between the Pizzas table and the Orders table.
This table, let's call it "Order_Details"(MySQL Workbench automatically called it "Orders_has_Pizzas") must reference both "Orders" and "Pizzas".
Now, since "Orders" already references the Users table in an identifying relationship, that's part of the primary key of "Orders".
And let's get that rule out once again:
- "In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. "
What this means is that you must reference the entire primary key. If I delete the "Order_Users_id" key, I'll get a 1005 error upon trying to create the database.
My question is simply: is there a way around this? Because as it is right now, I have that User id mentioned in 3 different tables.
Or, am I not understanding it properly and is it indeed necessary to do this for the sake of not having to query different tables for that data?
EDIT: People seem to disagree with me on the relation between Users and Orders being identifying.
I don't see how an individual order can be identified without knowing the id of the user. After the order is made, someone is going to have to deliver the pizza, meaning they'll need to know where to deliver it. That data is in the Users table. Therefor, the Users_id is part of the identity of a single order.
That's how I see it anyway. If I'm wrong, please explain why.
EDIT 2: Thanks to a_horse_with_no_name for clarifying the concept of "identity" in terms of databases, I see the error of my logic now. Info can be found in the comments.