Question

I build a like system for a website and I'm front of a dilemma.

I have a table where all the items which can be liked are stored. Call it the "item table".

In order to preserve the speed of the server, do I have to :

  • add a column in the item table. It means that I have to search (with a regex in my PHP) inside a string where all the ID of the users who have liked the item are registered, each time a user like an item. This in order verify if the user in question has (or not) already liked the item before. In this case, I show a different button on my html.

Problem > If I have (by chance) 3000 liked on an item, I fear the string to begin very big and heavy to regex each time ther is a like on it...

  • add a specific new table (LikedBy) and record each like separately with the ID of the liker, the name of the item and the state of the like (liked or not).

Problem > In this case, I fear for the MySQL server with thousand of rows to analyze each time a new user like one popular item...

Server version: 5.5.36-cll-lve MySQL Community Server (GPL) by Atomicorp

Should I put the load on the PHP script or the MySql Database? What is the most performant (and scalable)?

If, for some reasons, my question does not make sens could anyone tell me the right way to do the trick? thx.

Was it helpful?

Solution

You have to create another table call it likes_table containing id_user int, id_item int that's how it should be done, if you do like your proposed first solution your database won't be normalized and you'll face too many issues in the future.

To get count of like you just have to

 SELECT COUNT(*) FROM likes_table WHERE id_item='id_item_you_are_looking_for';

To get who liked what:

 SELECT id_item FROM likes_table WHERE id_user='id_user_you_are_looking_for';

No regex needed nothing, and your database is well normalized for data to be found easily. You can tell mysql to index id_user and id_item making them unique in likes_table this way all your queries will run much faster

OTHER TIPS

With MySQL you can set the user ID and the item ID as a unique pair. This should improve performance by a lot.

Your table would have these 2 columns: item id, and user id. Every row would be a like.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top