Mysql更新列首次出现每个用户名

时间:2015-08-07 18:46:24

标签: mysql

我试图标记每个用户名每天的第一次出现。 我已经知道所有关于标记为dupe = 1的人。当天的第一个应该设置为dupe = 2.

就像外行人一样,如果第一次输入此用户名,则标记列= 2.每天都这样做。

基于这个问题https://stackoverflow.com/a/12065956/1811162我可以做到这个

Select *
from (
     select * from table WHERE dupe=1 order by date desc
     ) x
group by date

返回我要查找的每个副本中的一个成员,但我想设置一个= 2.我无法将此更新声明。或者这甚至可以作为更新声明吗?我只想要第一个成员设置。

我想要的结果是 -

Select username, dupe where dupe!= 0;

Day 1
Bob   - 2
Kathy - 2
Bob   - 1
Kathy - 1
Kathy - 1

Day 2
Kathy - 2
Kathy - 1
Bob - 2
Kathy - 1

我尝试的是

UPDATE table set dupeflag=2 from (
select * from
from (
    select * from table WHERE dupeflag=1 order by date desc
    ) x
group by date
)

但没有运气。可能非常错误

1 个答案:

答案 0 :(得分:1)

我为此添加了一个新的标记列,并且还有助于解决您的其他问题here

演示模式设置

create table table1
(
    id int auto_increment primary key,
    username varchar(30) not null,
    `date` date not null,
    dupeFlag int null, --  <---- New flag column, nullable, ignored on inserts below
    firstFlag int null --  <-- was first dupe for day? 2=yes, ignored on inserts below
);

insert table1 (username,`date`) values ('john','2015-01-01');
insert table1 (username,`date`) values ('kim','2015-01-01');
insert table1 (username,`date`) values ('john','2015-01-01');
insert table1 (username,`date`) values ('john','2015-02-01');
insert table1 (username,`date`) values ('john','2015-03-01');
insert table1 (username,`date`) values ('john','2015-03-01');
insert table1 (username,`date`) values ('kim','2015-01-01');
insert table1 (username,`date`) values ('kim','2015-02-01');

更新声明,根据PK ID设置 dupes 优先一天

update table1 t1
join 
(   select username,`date`,count(*) as theCount,min(id) as minForGroup
    from table1
    group by username,`date`
    having theCount>1
) inr
on inr.username=t1.username and inr.`date`=t1.`date`
set dupeFlag=1,
firstFlag=if(id=inr.minForGroup,2,666);


select * from table1;
+----+----------+------------+----------+-----------+
| id | username | date       | dupeFlag | firstFlag |
+----+----------+------------+----------+-----------+
|  1 | john     | 2015-01-01 |        1 |         2 |
|  2 | kim      | 2015-01-01 |        1 |         2 |
|  3 | john     | 2015-01-01 |        1 |       666 |
|  4 | john     | 2015-02-01 |     NULL |      NULL |
|  5 | john     | 2015-03-01 |        1 |         2 |
|  6 | john     | 2015-03-01 |        1 |       666 |
|  7 | kim      | 2015-01-01 |        1 |       666 |
|  8 | kim      | 2015-02-01 |     NULL |      NULL |
+----+----------+------------+----------+-----------+
8 rows in set (0.00 sec)