Create a view with column num_rows - MySQL

后端 未结 7 1417
[愿得一人]
[愿得一人] 2020-12-10 06:41

I need to create a view that has a column named row_num where it will be inserted the row number, just like an auto increment in a normal table.

Let\'s say I\'ve thi

7条回答
  •  感情败类
    2020-12-10 07:18

    When using the solution from @dazito you might encounter an issue with the counter continually incrementing from query to query, for example when your application reuses a session, like with JPA / Hibernate. For example:

    Query 1:

    | country | name | price | row_num |
    ------------------------------------
    | US      | john |  20   |    1    |
    | France  | Anne |  10   |    2    |
    | Sweden  | Alex |  5    |    3    |
    

    Query 2:

    | country | name | price | row_num |
    ------------------------------------
    | US      | john |  20   |    4    |
    | France  | Anne |  10   |    5    |
    | Sweden  | Alex |  5    |    6    |
    

    etc.

    One solution to this is to join the main query with a (one-time) call to the counter function and parameterize the function (the 'reset' parameter below) to let it know it is the first call.

    delimiter //
    CREATE FUNCTION `func_inc_var_session`(reset BIT) RETURNS int
        NO SQL
        NOT DETERMINISTIC
         begin
          IF reset THEN
            SET @var := 0;
          ELSE
            SET @var := IFNULL(@var,0) + 1;
          END IF;
          return @var;
         end
         //
    delimiter ;
    

    Now you can call the function in your view query with the reset parameter set to 1 to set the function's counter variable back to 0, and with 0 to increment the counter. The function will only get called once with 1 as a parameter when joining with it as below:

    CREATE OR REPLACE VIEW country_view (country, name, price, row_num) 
    AS SELECT country, name, price, func_inc_var_session(0) 
    FROM country
    JOIN (SELECT func_inc_var_session(1)) r
    

    Now you are guaranteed row number 1, 2, 3 every time.

提交回复
热议问题