简体   繁体   English

在什么情况下应该使用数据库触发器?

[英]In what situations should I use DB Triggers?

I have two tables, one which stores articles and the number of votes it has received: 我有两个表,一个表用于存储文章及其获得的票数:

| article_id | visitor_votes | member_votes | voting_opened |
-------------------------------------------------------------
| 1          | 12            | 394          | Y             |
| 3          | 94            | 5821         | Y             |

I also have another table which keeps track of which user voted for which article 我还有另一个表格,用于跟踪哪个用户为哪个文章投票

| vote_id | user_id | article_id | date    |
--------------------------------------------
| 1       | 12      | 1          | 7/28/2012
| 2       | 23      | 3          | 7/28/2012

One user can only place one vote per transaction. 一位用户每次交易只能投一票。 I currently use a trigger that increments the number of votes in the articles table every time a record is inserted into the votes table. 我目前使用触发器,每当一条记录插入投票表时,该触发器就会增加商品表中的投票数。 Is this good practice or should I be doing this in my application (PHP web-based website)? 这是一种好习惯还是应该在我的应用程序(基于PHP Web的网站)中进行? I also want to stop voting after a certain number of votes (voting_opened = N), should I use a trigger to check if the total votes (visitor_votes + member_votes >= 6000) and then update the article row to set voting_opened = N? 我还想在经过一定数量的投票后停止投票(voting_opened = N),我是否应该使用触发器来检查总投票数(visitor_votes + member_votes> = 6000),然后更新文章行以设置voting_opened = N? Or is this something I should be doing in my application as well? 还是这也是我应该在应用程序中执行的操作? I need a solution that is scale-able because I will have thousands of votes for possibly hundreds of articles and I don't want to run into a case where the number of votes goes over the threshold because an update didn't update quick enough or whatever. 我需要一个可扩展的解决方案,因为我将获得数千张选票,可能涉及数百篇文章,并且我不希望遇到由于更新未足够快而导致选票数超过阈值的情况管他呢。 Can someone shed some light on this scenario please? 有人可以阐明这种情况吗?

Thank you! 谢谢!

Both solutions are valid and should work equally well. 两种解决方案都是有效的,并且应该同样有效。

You can try something like this in the application 您可以在应用程序中尝试这样的事情

UPDATE articles SET 
    visitor_votes = visitor_votes + 1
    voting_opened = IF(visitor_votes + member_votes >= 6000, 'N', 'Y')
WHERE 
article_id = xxxx
AND voting_opened = 'Y'

then check affected rows and if it is > 0 insert the row in the votes table. 然后检查受影响的行,如果该行> 0,则将该行插入投票表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM