简体   繁体   English

行更改时,SQL查询未更新表

[英]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: 我的SQL查询有一个小问题,最好通过一个示例来说明:

1) If booking.status is set to open, then it is counted when the method is run and presented in the datatable. 1)如果booking.status设置为open,则在运行该方法并将其显示在数据表中时对其进行计数。 Let's take plot_id=15 , as you can see here it appears 3 times in the table. 让我们以plot_id=15 ,如您所见,它在表中出现了3次。

在此处输入图片说明

在此处输入图片说明

2) As a result, the change will be reflected in plot.jobs 2)结果,更改将反映在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. 3)但在booking.status更新的情况下,该方法在运行时或在数据表中显示时将不再计数。 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 4)如果未出现在列表中,则表示plot.plot_id=15应该为0 ...为什么在plot.jobs仍为3

在此处输入图片说明

I think I am missing out an SQL query in the if (dtCounts.Rows.Count > 0) {...} conditional. 我认为我在if (dtCounts.Rows.Count > 0) {...}有条件的情况下错过了SQL查询。 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 ? 更新plot.jobs时,如何计算booking.status更改的实例?

This is my code so far: http://pastebin.com/pYu17aVR 到目前为止,这是我的代码: 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) (对不起,由于某些原因,S / O不允许我将代码粘贴到答案中,它始终返回错误消息)

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: 相反,您可以将查询合并为一个查询,该查询也可以处理null:

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? 有几件事情要注意-如果预订表中没有该plot_id的数据,该怎么办? What about new plots being added? 如何添加新地块?

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

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