Bring rows in a database table that have data in all columns to the front
P粉504080992
P粉504080992 2023-08-18 15:48:44
0
1
544
<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>
P粉504080992
P粉504080992

reply all(1)
P粉677573079

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,      -- 非空年龄优先
    age,              -- 按年龄升序排序
    address IS NULL,  -- 非空地址优先
    address;          -- 按地址升序排序
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!