I am setting up a voting program where I want to limit users to one vote up. I have two tables: (a) subject table and (b) vote table.
**Subject_Table**
SID Subject Total_Votes
1 Cows 5
2 Chickens 3
**Vote_Table**
VID Subject User Voteup
1 Cows John 1
Total votes equal votes from all users. Voteup can only equal 1 if an subject is voted on. I have made a unique value pair with Subject and User with the following statement without any problems:
ALTER TABLE Vote_Table ADD UNIQUE limitvote(Subject,User);
When a subject is voted on for the first time the following queries execute:
$sql="INSERT INTO Vote_Table (Subject, User,Voteup) VALUES ('$Subject', '$User', '$Voteup') ON DUPLICATE KEY UPDATE up=1";
$q = "UPDATE Subject_Table SET Total_Votes = $votes_up= //current votes plus 1;
Even if John votes twice the vote will always equal 1 in the Vote_Table due to ON DUPLICATE KEY UPDATE up=1. But this is not so in the Subject_Table. Without a constraint, John could vote infinitely. The constraint must be the subject-user pair. Constraints cannot be only Subject or User since John can vote for other subjects and other users can vote for Cows.
How can I check Vote_Table to see if the unique Subject-User pair (Cows and John)) exists before I update Subject_Table?
You can incorporate it into the
WHEREclause:That said, I’m not sure that you really need
Subject_Tableat all; you can create a view on theVote_Tablethat will give you the same information, without having to create separate table. (See the the Wikipedia article on Database normalization.) That could look like this: