使用mysql2 连接数据库时,怎么让联表查询返回结构化、层级嵌套的数据呢?
发布于 6 年前 作者 my-soul 2202 次浏览 来自 问答

大家好, 请问: 使用mysql2 连接数据库时,怎么让联表查询返回结构化,层级嵌套的数据呢?

const sql = 'SELECT * FROM t_teacher LEFT JOIN t_student ON t_teacher.id = t_student.teacher_id';
mysql2.query(sql, () => {
});

// 希望返回的数据结构
const result = [
	{
		name: '张老师',
		students: [
			{
				name: '小明',
			},
		],
	},
];

2 回复

这东西只能在逻辑层处理吧? query出来的结果就是你sql语句的结果啊

嗯,要把返回的数据处理成我想要的有点麻烦, mysql有一个 nestTables 的配置项,而mysql2 我没找到这个类似的功能。

var options = {sql: '...', nestTables: true};
connection.query(options, function (error, results, fields) {
  if (error) throw error;
  /* results will be an array like this now:
  [{
    table1: {
      fieldA: '...',
      fieldB: '...',
    },
    table2: {
      fieldA: '...',
      fieldB: '...',
    },
  }, ...]
  */
});

回到顶部