将嵌套选择中的列分组

时间:2018-11-19 20:02:48

标签: mysql sql

我有一个表table1,其中包含以下列:

id (INT)
label (VARCHAR)
value (INT)

我想同时检索value列的平均值,value最大的整行和最低value的行。像这样:

{
    average: xxx,
    maxval: {
        id: x,
        label: x,
        value: x
    },
    minval: {
        id: x,
        label: x,
        value: x
    }
}

尝试以下查询:

SELECT 
AVG(a.value) AS average, 
b.*,
c.*
FROM table1 a
INNER JOIN table1 b ON ( b.value = (SELECT MAX(value) FROM table1 WHERE label = "el")) 
INNER JOIN table1 c ON ( c.value = (SELECT MIN(value) FROM table1 WHERE label = "el")) 
WHERE a.label = "el";

但是这将返回单个级别中的所有字段,如下所示:

{
    average,
    id,
    label,
    value,
    id,
    label,
    value
}

也尝试过:

SELECT 
AVG(a.value) AS average, 
(SELECT b.* FROM table1 b WHERE ( b.value = (SELECT MAX(value) FROM table1 WHERE label = "el"))) AS maxval,
(SELECT c.* FROM table1 c WHERE ( c.value = (SELECT MIN(value) FROM table1 WHERE label = "el"))) AS minval
FROM table1 a
WHERE a.label = "el";

最后一个错误,因为我试图在多个列上使用单个别名。

使用MySQL 5.5。

1 个答案:

答案 0 :(得分:1)

您需要对每个查询进行单独的查询

SELECT q1.*, q2.*, q3.*
FROM (SELECT AVG(value)
      FROM  Table1) as q1
CROSS JOIN ( SELECT *
             FROM Table1
             ORDER BY value
             LIMIT 1) as q2
CROSS JOIN ( SELECT *
             FROM Table1
             ORDER BY value DESC
             LIMIT 1) as q3

您可以使用JSON_OBJECT(key1, value1, key2, value2, ... key(n), value(n))

 SELECT q1.*, 
    JSON_OBJECT("id", q2.id, "label", q2.label,"value", q2.value),
    JSON_OBJECT("id", q3.id, "label", q3.label,"value", q3.value)