如果存在具有特定值的另一列,我会尝试在用户名列中第一次出现任何值时设置另一列的值(按月间隔)。
create table table1
(
username varchar(30) not null,
`date` date not null,
eventid int not null,
firstFlag int null
);
insert table1 (username,`date`, eventid) values
('john','2015-01-01', 1)
, ('kim','2015-01-01', 1)
, ('john','2015-01-01', 1)
, ('john','2015-01-01', 1)
, ('john','2015-03-01', 2)
, ('john','2015-03-01', 1)
, ('kim','2015-01-01', 1)
, ('kim','2015-02-01', 1);
这应该导致:
| username | date | eventid | firstFlag |
|----------|------------|---------|-----------|
| john | 2015-01-01 | 1 | 1 |
| kim | 2015-01-01 | 1 | 1 |
| john | 2015-01-01 | 1 | (null) |
| john | 2015-01-01 | 1 | (null) |
| john | 2015-03-01 | 2 | 1 |
| john | 2015-03-01 | 1 | (null) |
| kim | 2015-01-01 | 1 | (null) |
| kim | 2015-02-01 | 1 | 1 |
我尝试使用连接作为 described here ,但它会更新所有行:
update table1 t1
inner join
( select username,min(`date`) as minForGroup
from table1
group by username,`date`
) inr
on inr.username=t1.username and inr.minForGroup=t1.`date`
set firstFlag=1;
最佳答案
如a1ex07 points out ,它需要另一个每行唯一约束来更新我需要的行:
update table1 t1
inner join
( select id, username,min(`date`) as minForGroup
from table1
where eventid = 1
group by username,month(`date`)
) inr
on inr.id=t1.id and inr.username=t1.username and inr.minForGroup=t1.`date`
set firstFlag=1;
添加 Id 列,并将其用于约束连接。
要仅允许满足另一列上的特定条件,您需要子查询中的 where 子句,否则它将尝试匹配不同的行,因为子查询将返回 eventid=2 的行,而更新查询将仅返回那些行eventid=1。
要使用每年间隔而不是每月,请将 group by 语句更改为使用年份。
关于mysql - 更新时间间隔内第一次出现的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48955447/