代码之家  ›  专栏  ›  技术社区  ›  neptune

对嵌套select中的列进行分组

  •  0
  • neptune  · 技术社区  · 6 年前

    我有一张桌子 table1 包含以下列:

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

    我想检索 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";
    

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

    使用MySQL5.5。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Juan Carlos Oropeza    6 年前

    你需要为每一个单独的查询

    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)