MySQL如何显示列和表的平均值

MySQL如何显示列和表的平均值

我正在尝试获得如下输出:

Average score
10
col1   col2  score
...


使用

SELECT AVG(Score), *
FROM (
SUM(...) AS col1
SUM(...) AS col2
SUM(...) AS Score
) AS T1


当我仅选择AVG(Score)或*而不同时选择两者时,此方法有效。有什么办法可以做到而无需重复代码?

这是我尝试时遇到的错误:

ERROR 1064 (42000) at line 27: You have an error in your SQL syntax; check
the manual that corresponds to your MySQL server version for the right
syntax to use near '*
FROM (
SELECT
    testresults.hostname AS Hostname,
    hostinfo.env A' at line 3

最佳答案

您不能将*与其他列一起使用。您可以执行以下任一操作:

 SELECT * FROM...


要么

 SELECT col1, col2, col3... FROM...


但不是

 SELECT col1, col2, col3, * FROM...


例:

mysql> SELECT id FROM users LIMIT 5;
+----+
| id |
+----+
| 18 |
| 22 |
| 23 |
| 26 |
| 27 |
+----+
5 rows in set (0.00 sec)

mysql> SELECT id, * FROM users LIMIT 5;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM users LIMIT 5' at line 1

关于mysql - MySQL如何显示列和表的平均值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42771625/

10-11 03:14