I’m making a site with PHP and MySQL. The big idea is that you can register and you can add objects to your profile. You can have only 1 profile, you can have multiple items(infinite, in theory) and each items can have multiple pictures(infinite, in theory).
I’m wondering how to best implement this in MySQL. I’ve had a very basic education on MySQL, in that I know how to make a table, what the various datatypes are, but things like foreign keys are something that’s buried in the back of my memory. I looked it up, but the understanding is coming a bit slow.
I could simply make 3 tables:
- Users_name + User_ID
- Item_ID + User_ID
- Item_ID + Picture_ID
Downside is that for every single search action, or profile view or even item view, I’d be querying the entire contents of the two last tables, which seems like overkill.
Can someone help me here?
Your schema is actually pretty good. Now, your fear is that you’d query the entire contents of the tables. This is very much not true, given a good index on your primary and foreign keys!
That rowset would return very quickly, even with hundreds of thousands of rows! The reason is because the query would use an index seek to find the row in
userswhere thatuser_idis. Likewise once you join it to theitemstable. Therefore, it’s just two very quick lookups to find all of the items you’re looking for, and it won’t ever have to scan the tables.SQL is absolutely optimized for this stuff. Please take advantage of it!