问题
I am new to web programming and need some expert advise. I am using SQL database for one of my website project. My website will display a list of topics with a Like and Dislike button. Logged in users will be able to click on the Like or dislike button for each topic. I am able to keep a count of likes and dislikes for each topics. So if a user clicks on a certain topic it will display the number of Likes and Dislikes for that particular topic, however what I am trying to achieve is when someone clicks on a particular Users profile it should display all the topics that user likes or dislikes. For example when we click on a users profile in Facebook, it displays all the comments or Likes of that particular user, how do I do something similar to that. I would like to know the data structure to implement this and query the data Thank you all. Regards, Aaf.
回答1:

This is a simple schema you could use. isLike is a boolean, true if it's a like, false if it's a dislike.
To query the total likesdislikes by topic
Select Count(*), Topic,isLike FROM LikesDislikes GROUP BY Topic,isLike
For all of a user's liked topics
SELECT topic FROM likesdislikes WHERE userName = 'user' AND isLike = true;
And so forth.
回答2:
If you have a table of Topics and a table of Users, you would add a table of Likes which links to both. Something like this:
User
----------
ID (int, PK)
Name (string)
etc...
Topic
----------
ID (int, PK)
Title (string)
etc...
Like
----------
ID (int, PK)
UserID (int, FK to User.ID)
TopicID (int, FK to Topic.ID)
IsLike (boolean)
etc...
So any time a user "likes" something you add a record to that table setting IsLike
to true
. If they "dislike" something then you add a record to that table setting IsLike
to false
. You can change around the terminology/names/types/etc. but the general idea is the same. A "like" becomes a linking record between a User
and a Topic
.
So when displaying the topic, you just select the count of records from the linking table which are associated with that topic. And when displaying a user you select the records from the linking table which are associated with that user.
回答3:
You could have three SQL tables:
Topics Ratings Users
You could then link the Users table via the Ratings table to the Topics table and do a query:
select * from Topics where RatingsUserID = UsersUserID
(pseudo code)
来源:https://stackoverflow.com/questions/14202168/sql-database-structure-for-like-and-dislike