ROW_NUMBER function page 2
MySQL has not ranking/window functions in its staff, but you can use variables in a SQL query directly. Particularly, the problem of numbering query result rows can be solved with using variables. Let's demonstrate it by example being considered on the previous page.
In the third line of the script, initializing of variable is accomplished. As a result, each row of Trip table will be joined the single-column row containing 0 (just Cartesian product).
In the first line of the script, variable is incrementing by 1, and this action takes place when calculating each next row in the sorting that is specified in ORDER BY clause. The numbering in this case corresponds to the sorting order.
If you omit the initialization of variable, you might obtain the correct result but without garantee. If you run the query (without initializing) once more in the current session of connection with database, you should obtain numbering which is starting from the maximal value of variable @i reached at the previous execution of the query.
We can get numbering of rows for each company separately, i.e. to imitate the behaviour of PARTITION BY in the query:
Let's introduce another variable for storing the company ID (@comp). When initializing variable, we assign unexisting ID (0, for example). Then for each row, the value of variable is comparing with company ID of the current row. If these values equal each other, @i is incrementing; if not - @i is resetting to 1. Finally, we assign the company ID from current row to variable @comp. The matter is that the comparison takes place before assigning, in so doing we compare the current value of company ID with the ID from previous row (in the given sorting order). Here the query is.
As we don't follow SQL(Structured Query Language) is a database computer language designed for the retrieval and management of data in relational database management systems (RDBMS), database schema creation and modification, and database object access control management.SQL Standard here, let's use MySQL IF function to make the query shorter.
To check the above queries, use console when selecting MySQL as target DBMS.