0

_

Hello everyone!

I have table

CREATE TABLE `labels` (
  `id` INT NULL AUTO_INCREMENT DEFAULT NULL,
  `name` VARCHAR(250) NULL DEFAULT NULL,
  `score` INT NULL DEFAULT NULL,
  `before_score` INT NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
);

And I Have This Table

CREATE TABLE `scores` (
  `id` INT NULL AUTO_INCREMENT DEFAULT NULL,
  `name_id` INT NULL DEFAULT NULL,
  `score` INT NULL DEFAULT NULL,
  `date` DATETIME DEFAULT NULL,
  PRIMARY KEY (`id`)
);

And i want have result where labels.score - have value last scores.score sorted by scores.date and labels.before_score where have value penultimate scores.score sorted by scores.date. Can I do This Only on Mysql slq and how?

Thanks.

ADD

For example i have this data on first table:

INSERT INTO `labels` (id, name, score, before_score) VALUES (1, 'John', 200, 123);
INSERT INTO `labels` (id, name, score, before_score) VALUES (2, 'Eddie', 2000, 2000);
INSERT INTO `labels` (id, name, score, before_score) VALUES (3, 'Bob', 400, 3101);

And second table

INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('1','1','12','2013-07-10');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('2','2','2000','2013-05-04');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('3','3','654','2012-09-12');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('4','1','123','2013-12-17');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('5','1','200','2014-04-25');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('6','3','3101','2013-12-02');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('6','2','2000','2015-12-02');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('6','3','400','2013-12-02');
4

1 回答 1

0

If I understand correctly, you need the last two scores for each name_id.

I would tackle this with temporary tables:

Step 1. Last score:

create temporary table temp_score1
    select name_id, max(`date`) as lastDate
    from scores
    group by name_id;
-- Add the appropriate indexes 
alter table temp_score1
    add unique index idx_name_id(name_id),
    add index idx_lastDate(lastDate);

Step 2. Penultimate score. The idea is exactly the same, but using temp_score1 to filter the data:

create temporary table temp_score2
    select s.name_id, max(`date`) as penultimateDate
    from scores as s
        inner join temp_score1 as t on s.nameId = t.nameId
    where s.`date` < t.lastDate
    group by name_id;
-- Add the appropriate indexes
alter table temp_score2
    add unique index idx_name_id(name_id),
    add index idx_penultimateDate(penultimateDate);

Step 3. Put it all together.

select 
    l.id, l.name,
    s1.lastScore, s2.penultimateScore
from
    `labels` as l
    left join temp_score1 as s1 on l.id = s1.name_id
    left join temp_score2 as s2 on l.id = s2.name_id

You can put this three steps inside a stored procedure.

Hope this helps you.

于 2013-02-17T19:49:00.543 回答