MySQL: Sorting duplicate numbers ascendingly
P粉763748806
2023-07-25 12:41:47
<p>I have a table that looks like this: </p>
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>values</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>2</td>
</tr>
<tr>
<td>5</td>
<td>2</td>
</tr>
<tr>
<td>6</td>
<td>2</td>
</tr>
</tbody>
</table>
<p>I want to sort them ascendingly this way in some kind of loop. </p>
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>values</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>5</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
</tr>
<tr>
<td>6</td>
<td>2</td>
</tr>
</tbody>
</table>
<p>I believe this can be done easily with PHP, but I wanted to see if I could do it with SQL. </p>
Use the ROW_NUMBER() window function in the ORDER BY clause:
You can take a look at this demo.