I would like to select datas from an alone table with two columns, for a value in the first column there may be only one or multiples different values for the second columnn, but one value in the second can be associated to only one in the first. Both are not unique individually and even concatenated. Example :
col_1 col_2
===== =====
a x
a y
b z
c w
b z
c w
Let’s say the col_1 is a group, col_2 a group chapter, and I need to associate a number to each of these chapters relative to their group; needs this number to be deterministic so rows can move and number kept during the lifecycle of the table. The result of the query should be then :
col_1 col_2 generated_col
===== ===== =============
a y 1
a x 2
b z 1
c w 1
col_1 + col_2 become unique in the result set, so each new value of col_2 for the same col_1 value gets a +1 to his generated_col.
Is there a way to do this directly in a select query ?
Important note : the MySQL server is on version 5.5
2
Answers
This working as expected :
Largely inspired by Tim's answer
On MySQL 8+, you may use the
ROW_NUMBER
window function:A workaround, for MySQL 5.7 and earlier: