Create a view with column num_rows - MySQL

后端 未结 7 1421
[愿得一人]
[愿得一人] 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:22

    Try to apply this query to your view -

    CREATE TABLE testing (
      id int(11) NOT NULL DEFAULT 0,
      country varchar(255) DEFAULT NULL,
      name varchar(255) DEFAULT NULL,
      age int(11) DEFAULT NULL,
      price int(11) DEFAULT NULL,
      PRIMARY KEY (id)
    );
    
    INSERT INTO testing(id, country, name, age, price) VALUES
      (1, 'US', 'john', 22, 20),
      (2, 'France', 'Anne', 10, 15),
      (3, 'Sweden', 'Alex', 49, 10),
      (4, 'France', 'Anne', 11, 16);
    
    SELECT
      t1.*, COUNT(*) row_num
    FROM testing t1
      LEFT JOIN testing t2
        ON t2.name < t1.name OR (t2.name = t1.name AND t2.id <= t1.id)
     GROUP  BY t1.name, t1.id;
    
    +----+---------+------+------+-------+---------+
    | id | country | name | age  | price | row_num |
    +----+---------+------+------+-------+---------+
    |  3 | Sweden  | Alex |   49 |    10 |       1 |
    |  2 | France  | Anne |   10 |    15 |       2 |
    |  4 | France  | Anne |   11 |    16 |       3 |
    |  1 | US      | john |   22 |    20 |       4 |
    +----+---------+------+------+-------+---------+
    
    • This query does not use any user variables, so it wotks in views.
    • Additional condition in ON clause helps to implement duplicated values in name field.

提交回复
热议问题