如何使用express在nodejs中进行mysql“梯形图”查询

时间:2018-01-26 00:31:38

标签: mysql node.js express

我遇到了问题,当我想用​​nodejs,express和mysql以“梯形”形式进行查询并返回一个json时,它对我不起作用,我想要的结构是:

  static_assert(std::size(U"") == 3);
  static_assert(std::size(u"") == 5);

  constexpr auto& test = tr<char16_t>(U""_c);
  static_assert(std::is_same<decltype(test), const char16_t(&)[5]>{});

  for(std::size_t i=0; i<std::size(u""); ++i) {
    assert(test[i] == u""[i]);
    std::cout << i << ": " << test[i] << std::endl;
  }

我正在使用forEach函数,我也尝试使用回调函数。

1 个答案:

答案 0 :(得分:0)

您需要连接所有3个表,然后遍历结果并构建嵌套对象。

var mysql = require("mysql");
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
var sql = `SELECT d.dev_id, d.dev_name, c.cont_id, c.cont_name, a.act_id, a.acti_id
           FROM devices AS d
           LEFT JOIN controllers AS c ON c.dev_id = c.dev_id
           LEFT JOIN actions AS a ON a.cont_id = c.cont_id`;
con.connect(err => {
    if (err) {
        throw err;
    }
    conn.query(sql, (err, result, fields) => {
        if (err) {
            throw err;
        }
        var devices = {};
        $result.forEach(({dev_id, dev_name, cont_id, cont_name, act_id, acti_id}) => {
            devices[dev_id] = devices[dev_id] || {id: dev_id, name: dev_name, controllers: {}};
            devices[dev_id].controllers[cont_id] = devices[dev_id].controllers[cont_id] || {id: cont_id, name: cont_name, actions: {}};
            devices[dev_id].controllers[cont_id].actions[act_id] = {id: act_id, acti_id: acti_id};
        });
    });
    // do something with devices here
});

请记住,所有mysql查询代码都是异步的,因此您无法正常返回值。你需要使用回调或承诺。

devices变量如下所示:

{
    devid1: {
        id: "devid1",
        name: "devname1",
        controllers: {
            contid1: {
                id: "contid1",
                name: "contname1",
                actions: {
                    actionid1: {
                        id: "actionid1",
                        acti_id: "acti_id1"
                    },
                    actionid2: {
                        id: "actionid2",
                        acti_id: "acti_id2"
                    }
                }
            },
            contid2: {
                id: "contid2",
                name: "contname2",
                actions: {
                    actionid3: {
                        id: "actionid3",
                        acti_id: "acti_id3"
                    }
                }
            }
        |
    }
}