0

我有两个表,第一个是“users_counts”

 id         int(11) AUTO_INCREMENT
 name       varchar(250)

我有第二张表“counts_data”

 id       int(11) AUTO_INCREMENT
 id_user  int(11) 
 count    int(11) 
 date     datetime

我想从第一个表中选择所有记录并从第二个表中获取一些数据,然后我想合并它们。我想创建临时(对于一个请求)列,其中在第二个表中按日期顺序收集最后一个计数,在第二个列中,在第二个表中按日期顺序收集倒数第二个计数。

INSERT INTO `users_counts` (`id`,`name`) VALUES ('1','John');
INSERT INTO `users_counts` (`id`,`name`) VALUES ('2','Michael');
INSERT INTO `users_counts` (`id`,`name`) VALUES ('3','Den');

INSERT INTO `counts_data` (`id`,`id_user`, `count`, `date`) VALUES ('1','1', '200', '2012.09.09');
INSERT INTO `counts_data` (`id`,`id_user`, `count`, `date`) VALUES ('2','1', '212', '2012.09.01');
INSERT INTO `counts_data` (`id`,`id_user`, `count`, `date`) VALUES ('3','2', '20', '2012.01.09');
INSERT INTO `counts_data` (`id`,`id_user`, `count`, `date`) VALUES ('4','3', '210', '2012.02.09');
INSERT INTO `counts_data` (`id`,`id_user`, `count`, `date`) VALUES ('5','3', '2033', '2012.03.09');
INSERT INTO `counts_data` (`id`,`id_user`, `count`, `date`) VALUES ('6','3', '1', '2012.04.09');

最后,在一个请求之后,我想得到这样的东西

id  name      count  count_before
1   John      200    212
2   Michael   20     0
3   Den       1      2033

谢谢。

4

2 回答 2

1

另一种可能的方法是:

select uc.id,
       uc.name,
       (select count 
          from counts_data cd 
          where cd.id_user = uc.id
          order by date desc limit 1) as count,
       ifnull((select count 
                 from counts_data cd 
                 where cd.id_user = uc.id 
                 order by date desc limit 1 offset 1),0) as count_before
from users_counts uc;

由于每行/记录只需要 counts_data 中的一个值,因此可以在 mySQL 中使用内联查询

SQL小提琴

于 2013-02-19T15:19:12.543 回答
0
select  uc.id
,       uc.name
,       cd1.count
,       cd3.count as count_before
from    users_counts uc
left join
        counts_data cd1
on      cd1.id_user = uc.id
        and cd.date = 
        (
        select  max(date)
        from    counts_data cd2
        where   cd2.id_user = uc.id_user
        )
left join
        counts_data cd3
on      cd3.id_user = uc.id
        and cd.date = 
        (
        select  max(date)
        from    counts_data cd4
        where   cd4.id_user = uc.id_user
                and cd4.date <> cd1.date
        )
于 2013-02-19T15:11:26.187 回答