Is it possible to sort the order in which columns are returned in a mysql SELECT statement?

前端 未结 2 1880
既然无缘
既然无缘 2021-01-27 16:21

Imagine two questions from an online survey:

  1. Do you like apples?

Result stored in mysql db column \"q1\" as

相关标签:
2条回答
  • 2021-01-27 16:45

    Thanks @user2864740 and @sgeddes for your prompt replies.

    SURVEY SAYS: It is NOT possible to sort returned columns in a SELECT statement using mysql without using dynamic sql.

    The solution I came up with uses a temporary table and is similar to the example below. While perhaps less than ideal, it answered the mail for what I needed. Curious if there is a better way to do the same thing or if I messed anything else up below.

    DROP TEMPORARY TABLE IF EXISTS orderedSums;
    SET @q1Sum = (SELECT SUM(q1) FROM myTable);
    SET @q2Sum = (SELECT SUM(q2) FROM myTable);
    
    CREATE TEMPORARY TABLE orderedSums (
        qNum VARCHAR(5),
        qSum INT
    );
    
    INSERT INTO orderedSums
        VALUES ('q1Sum', @q1Sum),('q2Sum', @q2Sum);
    
    SELECT qNum, qSum
        FROM orderedSums
        ORDER BY qSum DESC;
    

    Returns multiple rows of SUMs sorted in descending order from myTable.

    0 讨论(0)
  • 2021-01-27 16:55

    Assuming I'm understanding your question correctly, you could use a case statement:

    SELECT CASE WHEN SUM(q1) > SUM(q2) THEN SUM(q1) ELSE SUM(q2) END AS q1Sum,
       CASE WHEN SUM(q1) > SUM(q2) THEN SUM(q2) ELSE SUM(q1) END AS q2Sum 
    FROM myTable 
    

    Actually this would mislabel the columns -- you cannot alter the name of the column without using dynamic sql.

    0 讨论(0)
提交回复
热议问题