MySQL查询结果为所需格式

时间:2018-04-15 03:48:23

标签: mysql

大家好我对MySQL的查询有疑问

我有像这样的表名TEST

      const monthsEnum = {
        "_id": "year",
        "1": "January",
        "2": "February",
        "3": "March",
        "4": "April",
        "5": "May",
        "6": "June",
        "7": "July",
        "8": "August",
        "9": "September",
        "10": "October",
        "11": "November",
        "12": "December"
    };

    app.get('/polute', function (req, res) {
      Air_pollution.aggregate([
      { "$match": {
          "CREATE_DATE": {
              "$lte": new Date(),
              "$gte": new Date(new Date().setDate(new Date().getDate()-120))
          }
      } },
      { "$group": {
          "_id": {
              "month": { "$month": "$CREATE_DATE" },
              "year": { "$year": "$CREATE_DATE" }
          },
          "avgofozone": { "$avg": "$OZONE" }
      } },
      { "$group": {
          "_id": "$year",
          "avgs": {
              "$push": {
                  "k": { "$substr": ["$month", 0, -1 ] },
                  "v": "$avgofozone"
              }
          }
      } },
      { "$replaceRoot": {
          "newRoot": {
              "$mergeObjects": [
                  { "$arrayToObject": "$avgs" },
                  "$$ROOT"
               ]
          }
      } },
      { "$project": { "avgs": 0 } }
    ], (err, Air_pollution) => {
      console.log("naresh:" +JSON.stringify(Air_pollution));
      const polute = Object.keys(Air_pollution).reduce((p, c) => ({...p, monthsEnum[c]: Air_pollution[c]}), {});
      res.json(Air_pollution);
    }), 
expected output:
[
    { 
        "zone_type": "avgofozone", 
        "year": 2018, 
        "February": 21.07777777777778, 
        "March": 17.8, 
        "January": 17.8 
    }
] 

我想像这样进行查询输出

Column_1    Column_2    Class
5           9           A
2           6           B
4           3           B
7           3           C

如何/什么MySQL查询可以输出那样的? 感谢

2 个答案:

答案 0 :(得分:0)

我们可以使用GROUP_CONCATCONCAT的组合来实现此输出,应用于整个表:

SELECT
    CONCAT('[[',
           GROUP_CONCAT(Column_1, ',', Column_2 SEPARATOR '], ['),
           ']] , [''',
           GROUP_CONCAT(Class SEPARATOR ''', ''' ),
           ''']') AS output
FROM yourTable;

enter image description here

Demo

我觉得您可能正计划使用JSON数据。如果是这样,请查看MySQL的support for JSON functions。或者,您可能需要考虑在表示层/语言中处理此输出问题。

答案 1 :(得分:0)

我不知道你为什么要这样,但你可以使用mysql查询。响应是该格式的字符串。

查询:

SELECT
CONCAT(
    '[',
        GROUP_CONCAT(CONCAT('[', Column_1, ', ', Column_2, ']')),
        ', ',
        CONCAT('[',GROUP_CONCAT( CONCAT('''',Class), ''''), ']'),
    ']'
) AS result
FROM TEST
;

回复: [[5,9],[2,6],[4,3],[7,3],[' A',&#39 ; B'' B',' C']]