简体   繁体   中英

SQL query not updating table when row is changed

I am having a small problem with my SQL query that is best explained through an example:

1) If booking.status is set to open, then it is counted when the method is run and presented in the datatable. Let's take plot_id=15 , as you can see here it appears 3 times in the table.

在此处输入图片说明

在此处输入图片说明

2) As a result, the change will be reflected in plot.jobs

在此处输入图片说明

3) But in a case where booking.status is updated, then it is no longer counted when the method is run, or presented in the datatable. This is expected.

在此处输入图片说明

在此处输入图片说明

4) If it doesn't appear in the list, then it means the plot.plot_id=15 should be 0... why is it still 3 in plot.jobs

在此处输入图片说明

I think I am missing out an SQL query in the if (dtCounts.Rows.Count > 0) {...} conditional. Problem is I have no idea where to start implementing it. Can anyone please point me in the right direction? How can I account for instances where booking.status is changed, when updating plot.jobs ?

This is my code so far: http://pastebin.com/pYu17aVR

(sorry, for some reason S/O won't let me paste the code into the answer, it keeps returning an error message)

I'm not sure if i understood what you want to do excactly.

Have you ever thought to implement a trigger on update of booking status?

CREATE
    [DEFINER = { user | CURRENT_USER }]
    TRIGGER trigger_name
    trigger_time trigger_event
    ON tbl_name FOR EACH ROW
    trigger_body

trigger_time: { BEFORE | AFTER }

trigger_event: { INSERT | UPDATE | DELETE }

您在12-17行的粘贴容器清单中给出的更新语句是有条件的booking.plot_id is NULL (l.17)。

If I'm understanding your problem correctly, I don't see the need for looping at all. Instead, you can combine the queries into one, which can handle the nulls as well:

update plot p 
inner join (
  select sum(case when status = 'open' then 1 else 0 end) cnt, plot_id
  from booking
  group by plot_id
  ) p2 on p.plot_id = p2.plot_id
set p.jobs = p2.cnt

There are a couple things to be aware of -- what should happen if no data exists in the booking table for that plot_id? What about new plots being added?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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