mysql - 如果该状态已与该表的另一个属性一起存在,则停止将该表的属性更新为特定状态
问题描述
我有两张桌子。月_with_years 和months_with_years_status。我不希望超过一个month_with_year_id 的状态为“正在进行”。如果我尝试将 month_with_year_id 的状态更新为“正在进行”,而另一个 month_with_year_id 的状态为“正在进行”,我希望我的计数器显示 1 并停止更新。
CREATE TABLE `months_with_years` (
month_with_year_id INT(2) NOT NULL AUTO_INCREMENT,
month_with_year_mwy VARCHAR(50) NOT NULL,
PRIMARY KEY (month_with_year_id),
UNIQUE (month_with_year_mwy)
);
CREATE TABLE `months_with_years_status` (
month_with_year_id INT(2),
status_of_month_with_year VARCHAR(50),
FOREIGN KEY (month_with_year_id)
REFERENCES months_with_years (month_with_year_id)
);
delimiter $$
create trigger trigger_2
after insert on months_with_years
for each row
begin
insert into months_with_years_status(month_with_year_id,
status_of_month_with_year)
values (new.month_with_year_id,'Status has not been updated yet');
end$$
delimiter ;
insert into months_with_years
values(1,'1-2019'),(2,'2-2019'),(3,'3-2019');
update months_with_years_status
set status_of_month_with_year='Ongoing'
where month_with_year_id=1;
update months_with_years_status
set status_of_month_with_year='Ongoing'
where month_with_year_id=2;
当计数发生时,我试图获得 count_of_ongoing_status_YearMonth 值 1。
select count(*) as count_of_ongoing_status_YearMonth
from months_with_years_status
where status_of_month_with_year='Ongoing' having count(*) like '%Ongoing%' = 1;
解决方案
检查您只需要的计数
select count(*) as count_of_ongoing_status_YearMonth
from months_with_years_status
where status_of_month_with_year='Ongoing' having count(*) = 1;
可能是您每个月都需要这些_with_year_id .. 为此您可以使用 group by
select month_with_year_id , count(*) as count_of_ongoing_status_YearMonth
from months_with_years_status
where status_of_month_with_year='Ongoing'
group by month_with_year_id
having count(*) = 1;
推荐阅读
- java - 在学习 BFS、DFS 等寻路算法之前要学习哪些基础?
- google-maps - 是否可以只检索谷歌方向 API 中的步行旅程?
- java - 在java中的JSON文件中添加新键,值并更新键的现有值
- c# - 当控制台应用程序中的内容发生变化时,是否可以在固定位置显示字符串?
- c++ - 这两个类型测试对象的动态数组声明之间的区别?
- matlab - Matlab - 如何结合结构和循环来减少操作次数?
- swift - SwiftUI:如何在列表内的 NavigationLink 中删除插入符号
- android - 更新支付时出现“未找到类”org.apache.commons.codec.binary.Base64”异常
- git - 本地公司服务器上的 Git 服务器 + 文件
- swift - 斯威夫特:尝试使用闭包而不是#selector但不起作用