Row Rank in a MySQL View

前端 未结 2 1185
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 12:02

I need to create a view that automatically adds virtual row number in the result. the graph here is totally random all that I want to achieve is the last column to be create

2条回答
  •  眼角桃花
    2020-12-03 12:46

    Use:

    SELECT t.id,
           t.variety,
           (SELECT COUNT(*) FROM TABLE WHERE id < t.id) +1 AS NUM
      FROM TABLE t
    

    It's not an ideal manner of doing this, because the query for the num value will execute for every row returned. A better idea would be to create a NUMBERS table, with a single column containing a number starting at one that increments to an outrageously large number, and then join & reference the NUMBERS table in a manner similar to the variable example that follows.

    MySQL Ranking, or Lack Thereof

    You can define a variable in order to get psuedo row number functionality, because MySQL doesn't have any ranking functions:

    SELECT t.id,
           t.variety,
           @rownum := @rownum + 1 AS num
      FROM TABLE t,
           (SELECT @rownum := 0) r
    
    • The SELECT @rownum := 0 defines the variable, and sets it to zero.
    • The r is a subquery/table alias, because you'll get an error in MySQL if you don't define an alias for a subquery, even if you don't use it.

    Can't Use A Variable in a MySQL View

    If you do, you'll get the 1351 error, because you can't use a variable in a view due to design. The bug/feature behavior is documented here.

提交回复
热议问题