简体   繁体   English

选择,检查并插入是否满足条件

[英]SELECT, check and INSERT if condition is met

I have the following tables: Tour, Customer, TourCustomerXRef. 我有以下表格:Tour,Customer,TourCustomerXRef。 Assuming every Tour has a capacity Cap. 假设每个巡回赛都有容量上限。 Now a request arrives at the backend for a booking. 现在,一个请求到达后端进行预订。

What I need to do is: 我需要做的是:

  1. SELECT and count() all of the entries in TourCustomerXRef where the tourid=123 SELECT和count()TourCustomerXRef中的所有条目,其中Tourid = 123
  2. In the program code (or the query?): If count() < Cap 在程序代码(或查询?)中:如果count()<Cap
    1. True: INSERT into TourCustomerXRef, return success 正确:插入TourCustomerXRef,返回成功
    2. False: return an error False:返回错误

However, it might be possible that the backend api is being called concurrently. 但是,可能会同时调用后端api。 This could result into the SELECT statement returning a number under the max. 这可能导致SELECT语句返回最大值以下的数字。 capacity both times, resulting in the INSERT being executed multiple times (even though there is just one place left). 两次都具有最大容量,导致INSERT被执行多次(即使仅剩一个地方)。

What would be the best prevention for above case? 对于上述情况最好的预防方法是什么? set transaction isolation level serializable? 设置事务隔离级别可序列化? or Repeatable Read? 还是可重复读?

I'm worried that the application logic (even though it's just a simple if) could hurt the performance, since read and write locks would not allow the api to execute querys that just want to select the data without inserting anything, right? 我担心应用程序逻辑(即使只是一个简单的逻辑)也会损害性能,因为读写锁定将不允许api执行只想选择数据而不插入任何内容的查询,对吗?

(Using mariaDB) (使用mariaDB)

You can try using lock hint "FOR UPDATE" in the SELECT (mysql example): 您可以尝试在SELECT(MySQL示例)中使用锁定提示“ FOR UPDATE”:

BEGIN TRANSACTION;
SELECT * FROM TourCustomerXRef FOR UPDATE WHERE ...;
INSERT ...;
COMMIT;

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

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