mysql row_number() over(partition by )
时间: 2023-10-20 22:36:54 浏览: 98
MySQL does not have a built-in ROW_NUMBER() function like some other database systems (e.g., Oracle, SQL Server, PostgreSQL). However, you can achieve similar results using user-defined variables. Here's an example of how you can use user variables to generate row numbers within partitions:
```sql
SELECT
*,
@row_number := IF(@partition = partition_column, @row_number + 1, 1) AS row_number,
@partition := partition_column
FROM
your_table
ORDER BY
partition_column, ordering_column;
```
In the above query, `partition_column` is the column used for partitioning, and `ordering_column` is the column used for determining the order within each partition. Please replace `your_table` with the actual name of your table.
The query uses two user-defined variables: `@row_number` and `@partition`. The `IF` statement checks if the current row belongs to the same partition as the previous row (`@partition = partition_column`). If it does, it increments the row number (`@row_number + 1`). Otherwise, it resets the row number to 1. Finally, it updates the `@partition` variable with the partition value of the current row for comparison in the next iteration.
Keep in mind that user-defined variables have some caveats and limitations, so make sure to test and verify the results for your specific use case.
阅读全文