如果该表的另一个属性已经存在,则停止将该表的属性更新为特定状态

时间:2019-02-06 08:58:37

标签: mysql count

我有两个桌子。 months_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;

1 个答案:

答案 0 :(得分:0)

检查您只需要的计数

select count(*) as count_of_ongoing_status_YearMonth
from months_with_years_status 
where status_of_month_with_year='Ongoing' having count(*) = 1;

您可能需要每个month_with_year_id这些吗。.因此您可以使用分组依据

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;