[英]Is it possible to sort the order in which columns are returned in a mysql SELECT statement?
Imagine two questions from an online survey: 想象一下在线调查中的两个问题:
Result stored in mysql db column "q1" as 1 for Yes or 0 for No 结果存储在mysql db列“ q1”中,如果是,则为1 ;否则,为0
Result stored in mysql db column "q2" as 1 for Yes or 0 for No 结果存储在mysql db列“ q2”中,如果是,则为1 ;否则,为0
Imagine the following SELECT statement: 想象下面的SELECT语句:
SELECT SUM(q1) AS q1Sum, SUM(q2) AS q2Sum FROM myTable
Assume q1Sum=10 and q2Sum=12. 假设q1Sum = 10和q2Sum = 12。 The current SELECT statement would return: 当前的SELECT语句将返回:
+-------+-------+
| q1Sum | q2Sum |
+-------+-------+
| 10 | 12 |
+-------+-------+
But is it possible to return a different column order so that the greatest SUM is always the first column returned without changing the list order in the SELECT statement? 但是是否有可能返回不同的列顺序,以便最大的SUM始终是返回的第一列,而无需更改SELECT语句中的列表顺序?
SELECT SUM(q1) AS q1Sum, SUM(q2) AS q2Sum FROM myTable << something else >>
+-------+-------+
| q2Sum | q1Sum |
+-------+-------+
| 12 | 10 |
+-------+-------+
If q1Sum becomes greater than q2Sum the column order returned would revert to the original order. 如果q1Sum大于q2Sum,则返回的列顺序将恢复为原始顺序。
Why am I asking this question? 我为什么要问这个问题?
Assuming I'm understanding your question correctly, you could use a case
statement: 假设我正确理解了您的问题,则可以使用一个case
语句:
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
. 实际上,这将错误地标记列-您必须在不使用dynamic sql
情况下才能更改列的名称。
Thanks @user2864740 and @sgeddes for your prompt replies. 感谢@ user2864740和@sgeddes的迅速答复。
SURVEY SAYS: It is NOT possible to sort returned columns in a SELECT statement using mysql without using dynamic sql. 调查说:如果不使用动态sql,就无法使用mysql对SELECT语句中返回的列进行排序。
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. 返回从myTable降序排列的SUM的多行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.