我有2个有班级和主题的桌子。
我想在选择查询中用名称,学生人数和ID填充class_id。如何使用SQL或Knex做到这一点?
我尝试使用join,但是我只得到一个字段,而不是一行中的所有字段。
预期结果将是:
subject{
name: "data"
id: "data"
class: {
id: "data"
name: "data"
student_count: "data"
}
}
顺便说一句,用Knex或普通SQL回答会有所帮助!
答案 0 :(得分:0)
您必须使用内部联接或左联接。
在SQL中,它看起来像这样:
SELECT
s.id AS subject_id
, s.name AS subject_name
, c.id AS class_id
, c.name AS class_name
, c.student_count AS class_student_count
FROM subjects s
INNER JOIN class ON s.class_id = c.id
WHERE s.id = 1
在Knex中看起来像这样:
getOne: () => knex
.select( 's.id AS subject_id'
, 's.name AS subject_name'
, 'c.id AS class_id'
, 'c.name AS class_name'
, 'c.student_count AS class_student_count'
)
.from('subjects AS s')
.innerJoin('class AS c', 's.class_id', 'c.id')
.where('s.id': 1)
您将在AS之后获得一个变量名称为对象的对象。要使其成为您想要的格式,您必须创建一个映射器函数:
function mapToWantedFormat(subject) {
return {
name: subject.subject_name,
id: subject.subject_id
class: {
id: subject.class_id,
name: subject.class_name,
student_count: subject.class_student_count
}
};
};
例如,这样使用它:
module.exports.getOne = async (req, res, next) => {
try {
const subject = await getOne();
if (subject) {
res.status(200).json(mapToWantedFormat(subject));
} else {
res.status(404).json();
}
} catch (error) {
next(error);
}
};