1

I have 2 tables: users and items. Each item has a user#. So, if I want to find only items associated with a particular user I can:

SELECT * FROM items WHERE user_id = "$user_id";

But if there are thousands of items, searching through the table will take forever, right?

Is there a better way to go about doing this? Maybe a way to store all item numbers associated with a user into a field in the users table?

Thanks, Jason

1
  • Does every item has exactly one user? Commented May 25, 2011 at 20:09

3 Answers 3

3

Keep your current structure but add an index on user_id. This will mean that there is no need to search through "thousands of items" when doing lookups on this column.

Storing multiple values in a single column (a violation of First Normal Form) would be a step backwards as it would drastically reduce the efficiency of the opposite query to do lookups by item_id.

Sign up to request clarification or add additional context in comments.

Comments

1

No, it won't take forever. This is how it should be done, even if there were millions of records.

I noticed you quoted the user_id value... Isn't it a number field? The quotes are not needed.

Obviously the user_id should be an indexed field.

2 Comments

It's part of a php string: $query = "SELECT * FROM items WHERE user_id = '$user_id'"; This would work without the quotes?
Yeah... $query = "select * from items where user_id = $user_id"; and make sure you're sanitizing that variable so it cannot be sql injection.
1

Databases (not just MySQL) are pretty fast when searching. So it will take only few milliseconds to find such a row even in millions records. Databases use "indexes" for this - so if the column "user_id" is not primary key, then create index on user_id. Otherwise it could be slow.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.