简体   繁体   English

MYSQL检索上一个查询是更新还是插入

[英]MYSQL retrieve if last query was an update or an insert

I'm working on a rating system in PHP and MYSQL with votes up and votes down. 我正在用PHP和MYSQL开发一个评分系统,投票赞成和反对。

I have a database called votes which contains all the votes done by registered users (1 for up vote and -1 for a down vote) For every post that can rated there is a recap of all the up votes, down votes and also the net vote (up minus down votes). 我有一个名为votes的数据库,其中包含注册用户完成的所有投票(1代表赞成票,-1代表反对票)对于每个可以评级的帖子,都有所有赞成票,反对票和净额的摘要。投票(赞成票减去反对票)。

When someone up votes a post there is a INSERT ... ON DUPLICATE KEY UPDATE query that inserts or updates the table which contains all the votes. 当有人投票给帖子投票时,将有一个INSERT ... ON DUPLICATE KEY UPDATE查询,该查询插入或更新包含所有投票的表。 I then update the posts row with the new number of up votes, down votes and also the new net votes. 然后,我用上,下,新的净票数更新帖子行。

My problem is that I need to know if the first query was an insert or a update because if it is an update I will need to subtract the old vote and add the new one but id it is just an insert I don't need to subtract anything and just increment the vote. 我的问题是我需要知道第一个查询是插入还是更新,因为如果是更新,我将需要减去旧选票并添加新选票,但id只是一个插入,我不需要减去任何东西,然后增加投票。

I'd suggest that you do not optimize voting calculating prematurely, and after each new vote for some post you just recalculate all the votes for this post, regardless of whether that was INSERT or UPDATE that triggered recalculation. 我建议您不要过早优化投票计算,并且在对某个帖子进行每次新投票后,您只需重新计算该帖子的所有投票,无论是触发重新计算的INSERT还是UPDATE Then store the result to DB. 然后将结果存储到数据库。

Moreover, it is simpler throw out even total votes caching and calculate these on the fly, whenever you need. 此外,它甚至更容易抛出总票数缓存,并在需要时即时计算这些票数。

Only when you face performance problems, you should measure your expenses and check, what is the bottleneck. 仅当遇到性能问题时,才应衡量支出并检查什么是瓶颈。 Odds are that the voting calculation should be not the first thing to optimize in your application. 奇怪的是,投票计算不是您应用程序中要优化的第一件事。

Keep your life simpler. 让您的生活更简单。

Assuming you have a PRIMARY KEY on the table, you could do this: 假设您在桌上有一个PRIMARY KEY ,您可以这样做:

SET @last_insert_id := IFNULL(LAST_INSERT_ID(), 0);

INSERT ... ON DUPLICATE KEY UPDATE ...

SELECT IFNULL(LAST_INSERT_ID(), 0) <> @last_insert_id AS inserted;

If inserted is TRUE, a record was inserted, if FALSE, an existing record was updated. 如果inserted为TRUE,则插入一条记录;如果为FALSE,则更新现有记录。

Of course, this code assumes that the first LAST_INSERT_ID() was not set from an insertion into another table. 当然,此代码假定未从插入另一个表中设置第一个LAST_INSERT_ID()

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

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