Home  >  Q&A  >  body text

Bring rows in a database table that have data in all columns to the front

<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粉504080992P粉504080992428 days ago531

reply all(1)I'll reply

  • P粉677573079

    P粉6775730792023-08-19 12:28:57

    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;          -- 按地址升序排序
    

    reply
    0
  • Cancelreply