2016-11-07 30 views
3

我有一個SQL查詢:如何在續集中選擇個案查詢?

SELECT field1, field2, 
    CASE 
    WHEN field1=1 THEN 'a' 
    ELSE 'b' 
    END 
    AS field3 
FROM test 

,我想用sequelizejs實現它,

const params = { 
    attributes: //DO SELECT CASE, 
}; 

yield Model.findAll(params); 

誰能幫助我?謝謝。

回答

3

對於那些仍然在尋找這個答案的人

Model.findAll({ 
    attributes: [[models.sequelize.literal('CASE WHEN "field1" = true THEN 55 ELSE 23 END'), 'field3']] 
} 

Model.findAll({ 
    attributes: { include: [[models.sequelize.literal('CASE WHEN "field1" = true THEN 55 ELSE 23 END'), 'field3']]} 
} 

所以在我的例子中,當field1的是真的,那將返回55別的23.這將產生像查詢

SELECT CASE WHEN "field1" THEN 55 ELSE 23 END AS "field3" FROM "models" 

欲瞭解更多信息,你可以看看文檔 http://docs.sequelizejs.com/en/latest/docs/querying/#attributes