【发布时间】:2019-05-14 09:50:54
【问题描述】:
我想从连接表中选择一个字段并设置为2个不同条件的输出字段。
表员工:
---------------
empId | name
---------------
001 | James
002 | Alex
003 | Lisa
---------------
表 EmpDate:
------------------------------
empId | dateType | date
------------------------------
001 | REG | 2018-01-01
001 | TMN | 2018-12-31
002 | TMN | 2018-02-01
003 | REG | 2018-01-01
------------------------------
期望的输出:
----------------------------------------
empId | name | regisDate | TermDate
----------------------------------------
001 | James | 2018-01-01 | 2018-12-31
002 | Alex | | 2018-02-01
003 | Lisa | 2018-01-01 |
----------------------------------------
这是我的案例 SQL 脚本(在 MySQL 工作台上正常工作)。
SELECT emp.empId
, emp.name
, reg.date AS regisDate
, tmn.date AS termDate
FROM Employee AS emp
LEFT JOIN EmpDate AS reg
ON emp.empId = reg.empId
LEFT JOIN EmpDate AS tmn
ON emp.empId = tmn.empId
WHERE reg.dateType = 'REG'
AND tmn.dateType = 'TMN'
这是我当前的 Sequelize 代码(仍然无法选择所需的数据,因为它导致了 3 个输出字段)。
exports.getEmployeeData = () => {
const emp = db.Employee
const empDate = db.EmpDate
return emp.findAll({
raw: true,
attributes: [ 'empId', 'name', 'EmpDates.date' ],
include: [{
required: false,
model: empDate,
attributes: [],
where: { dateType: ['REG', 'TMN'] }
}]
})
}
我尝试使用这样的模型别名,但没有成功。
exports.getEmployeeData() = () => {
const emp = db.Employee
const empDate = db.EmpDate
return emp.findAll({
raw: true,
attributes: [
'empId',
'name',
'reg.date'
'tmn.date'
],
include: [{
required: false,
model: empDate,
attributes: [],
as: 'reg',
where: { dateType: 'REG' }
}, {
required: false,
model: empDate,
attributes: [],
as: 'tmn',
where: { dateType: 'TMN' }
}]
})
}
谁能指导我如何使用 sequelize findAll() 处理这种情况,或者如果我更改为 sequelize query() 会更好吗?提前致谢。
【问题讨论】:
-
错误是什么?
-
我认为我的代码不正确。你能解释一下我应该如何更正我的代码或包含模型别名如何工作。谢谢。
-
您的代码看起来不错,但我需要知道您遇到的错误是什么?
-
Here's my SQL script for the case (work correctly on MySQL workbench).那些 LEFT JOIN 被呈现为 INNER JOIN,这让我质疑这个评估。 -
empdate 表上的 PRIMARY KEY 是什么?
标签: javascript mysql node.js sequelize.js