I am sending sms to mobile numbers using many apis at the same time, now I want to ensure that only one sms should be sent to one mobile number.
I am selecting a row using the following query
SELECT s_contact_name, s_contact_number, i_sms_sent_count FROM contacts WHERE i_sms_sent_count = 0 ORDER BY ts_time_collected DESC LIMIT 1;
while selecting the row I want to set field i_sms_sent_count to 1 so that this row could not be selected again by any user.
Advertisement
Answer
One method is to do the update and then get the values. Assuming you have a contact_id column:
update contacts
set i_sms_sent_count = 1,
contact_id = (@contact_id := contact_id) -- does nothing except set the variable
where i_sms_sent_count = 0
order by ts_time_collected desc
limit 1;
Then get the information:
select * from contacts c where contact_id = @contact_id;
EDIT:
An alternative is:
start transaction;
select contact_id into @contact_id
from contacts
where i_sms_sent_count = 0
order by ts_time_collected desc
limit 1
for update;
update contacts
set i_sms_sent_count = 0
where contact_id = @contact_id;
commit transaction;