1

I have this view my mysql database

DROP VIEW IF EXISTS time_all;
CREATE VIEW `time_all` AS
SELECT `scans`.`datetime` FROM `time_clock`.`scans`
ORDER BY `scans`.`datetime` ASC;

I want to add unique rank value for each row in this view, can anyone tell me how to do that?

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
D.Kenny
  • 121
  • 1
  • 1
  • 12

2 Answers2

1

I'm not quite sure what you mean by "unique rank". Something like this probably does what you want:

CREATE VIEW `time_all` AS
    SELECT s.`datetime,
           (SELECT COUNT(*) FROM `time_clock`.`scans` s2 WHERE s2.datetime <= s.datetime) as rank
    FROM `time_clock`.`scans` s
    ORDER BY `scans`.`datetime` ASC;

MySQL supports neither window functions nor CTEs. Nor does it support variables in views. A correlated subquery is one of the few ways of doing this.

Strawberry
  • 33,750
  • 13
  • 40
  • 57
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Solved with this method

  delimiter $$
    DROP FUNCTION IF EXISTS `getRank`$$
    CREATE FUNCTION `getRank`() RETURNS int(11)
        DETERMINISTIC
    begin
    return if(@rankId, @rankId:=@rankId+1, @rankId:=1);
    end$$

Now if I want to use the function I created, just use it like this

CREATE VIEW time_all AS
SELECT getRank() AS 'rank', `scans`.`datetime` FROM `time_clock.scans`
ORDER BY scans.datetime ASC;
D.Kenny
  • 121
  • 1
  • 1
  • 12