[英]MYSQL How do I update a table only if a unique key pair of two columns does not exist in another table?
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.
我有两个表:(a)主题表和(b)投票表。
**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.
如果对某个主题进行投票,则投票只能等于1。 I have made a unique value pair with Subject and User with the following statement without any problems:
我使用以下语句与Subject和User建立了唯一的值对,没有任何问题:
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. 即使John投票了两次,由于ON DUPLICATE KEY UPDATE up = 1,Vote_Table中的投票也始终等于1。 But this is not so in the Subject_Table.
但这在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? 在更新Subject_Table之前,如何检查Vote_Table以查看是否存在唯一的Subject-User对(Cows和John)?
You can incorporate it into the WHERE
clause: 您可以将其合并到
WHERE
子句中:
UPDATE Subject_Table
SET Total_Votes = Total_Votes + 1
WHERE Subject = ...
AND NOT EXISTS
( SELECT 1
FROM Vote_Table
WHERE Subject = ...
AND User = ...
)
;
That said, I'm not sure that you really need Subject_Table
at all; 也就是说,我不确定您是否真的需要
Subject_Table
; you can create a view on the Vote_Table
that will give you the same information, without having to create separate table. 您可以在
Vote_Table
上创建一个视图,该视图将为您提供相同的信息,而无需创建单独的表。 (See the the Wikipedia article on Database normalization .) That could look like this: (请参阅有关数据库规范化的Wikipedia文章 。)如下所示:
CREATE VIEW Subject_View AS
SELECT Subject,
COUNT(1) AS Total_Votes
FROM Vote_Table
GROUP
BY Subject
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.