Bring rows in a database table that have data in all columns to the front
P粉5040809922023-08-18 15:48:44
0
1
671
<p>In MySQL5.7, I have a column with 28 columns and 4000 rows. I want to get all the rows that have data first or get the rows with the most columns of data first and then gradually get the data of other rows. How can I implement this? </p>
<p>For example:
Table: Student</p>
<table class="s-table">
<thead>
<tr>
<th style="text-align:center;">name</th>
<th style="text-align:center;">age</th>
<th style="text-align:center;">address</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center;">tan</td>
<td style="text-align:center;">10</td>
<td style="text-align:center;"></td>
</tr>
<tr>
<td style="text-align:center;">gib</td>
<td style="text-align:center;">10</td>
<td style="text-align:center;">california</td>
</tr>
<tr>
<td style="text-align:center;">hal</td>
<td style="text-align:center;"></td>
<td style="text-align:center;"></td>
</tr>
<tr>
<td style="text-align:center;">pur</td>
<td style="text-align:center;">12</td>
<td style="text-align:center;"></td>
</tr>
</tbody>
</table>
<p>Expected output: 'gib' should appear first, then 'tan' or 'pur' with only 1 column of data, and finally 'hal' without any data. </p>
Assuming that the name column will never have a null value, we can try:
SELECT name, age, address
FROM yourTable
ORDER BY
name,
age IS NULL, -- 非空年齡優(yōu)先
age, -- 按年齡升序排序
address IS NULL, -- 非空地址優(yōu)先
address; -- 按地址升序排序