最近寫的一個接口須要用到子查詢,而且子查詢的結果並非能夠在另一個查詢語句中直接看成in的選項,沒辦法區sequelize官網上看了一下如何直接使用原生語句html
看一段官網中代碼例子,一一說明前端
//1
sequelize.query('SELECT 1', {
logging: console.log,
plain: false,
raw: false,
type: Sequelize.QueryTypes.SELECT
})
//2
sequelize
.query('SELECT * FROM projects', { raw: true })
.then(projects => {
console.log(projects)
})
//3
sequelize.query('SELECT * FROM projects WHERE status = ?',
{ replacements: ['active'], type: sequelize.QueryTypes.SELECT }
).then(projects => {
console.log(projects)
})
//4
sequelize.query('SELECT * FROM projects WHERE status = :status ',
{ replacements: { status: 'active' }, type: sequelize.QueryTypes.SELECT }
).then(projects => {
console.log(projects)
})
複製代碼
sequelize中提供了query函數,用於直接操做原生語句mysql
該函數將返回兩個參數 - 結果數組和包含元數據的對象,對於mysql將是返一對象的兩個引用。程序員
query函數的第二個參數,是一個對象,對象裏面幾個經常使用參數進行說明。sql
對於查找條件where後面的字段api
對於替換where後面的變量,也可使用in關鍵字從數組匹配,也可使用通配符like%等 代碼以下:數組
//in關鍵字使用官網例子
sequelize.query('SELECT * FROM projects WHERE status IN(:status) ',
{ replacements: { status: ['active', 'inactive'] }, type: sequelize.QueryTypes.SELECT }
).then(projects => {
console.log(projects)
})
//like通配符關鍵字使用官網例子
sequelize.query('SELECT * FROM users WHERE name LIKE :search_name ',
{ replacements: { search_name: 'ben%' }, type: sequelize.QueryTypes.SELECT }
).then(projects => {
console.log(projects)
})
複製代碼
sequelize
.query('SELECT * FROM projects', {
model: Projects,
mapToModel: true // 若是有任何映射字段,則在這裏傳遞true
})
.then(projects => {
// Each record will now be an instance of Project
})
複製代碼
看一段我在開發過程當中怎麼使用的原生語句查詢 代碼以下:bash
let sqlRank = `SELECT userspk.avatar AS user_avatar,
userspk.gender AS user_gender,
userspk.nickname AS user_nickname,
a.id AS pk_record_id,
a.user_id,
a.answer_record,
a.pk_type,
MAX(score) AS score,
a.create_time
FROM (select * from pkrecord order by score desc,create_time asc) as a
INNER JOIN userspk AS userspk
ON a.user_id = userspk.user_id
WHERE a.status = 1
AND a.pk_type = 'noreal'
AND a.subject_id = :subject_id
GROUP BY user_id
ORDER BY a.score DESC
LIMIT 3;`
let pkRankResult= await ctx.main.query(sqlRank, {
replacements: {
subject_id: subject_id,
},
type: Sequelize.QueryTypes.SELECT }
);
複製代碼
注意 replacements中的subject_id變量是從前端請求獲取的參數值,是一個變量哦服務器
附件:微信
官網中原生語句查詢地址: docs.sequelizejs.com/manual/raw-…
歡迎你們關注個人公衆號——程序員成長指北。請自行微信搜索——「程序員成長指北」