简体   繁体   English

如何在sequelize.js中嵌套SQL函数?

[英]How to nest SQL functions in sequelize.js?

I'm using Sequelize.JS to connect to a MySQL database. 我正在使用Sequelize.JS连接到MySQL数据库。 I have the following table structure: 我具有以下表结构:

products
---------------------
id INT
name VARCHAR
price DECIMAL
price_special DECIMAL

I'd like to get the lowest price (or special_price , when available) and the highest price (or special_price when available). 我想获得最低price (或special_price ,如果有)和最高price (或special_price如果有)。 With raw SQL, I can do the following: 使用原始SQL,我可以执行以下操作:

SELECT 
    MIN(IF(`price_special` > 0, `price_special`, `price`)) AS `min`, 
    MAX(IF(`price_special` > 0, `price_special`, `price`)) as `max` 
FROM 
    `products`
;

I also know I can select a column wrapped by an SQL function in Sequelize, this way: 我也知道我可以通过Sequelize选择一个由SQL函数包装的列,方法是:

product.findOne({
    attributes: [
        [ Sequelize.fn('MIN', Sequelize.col('price')), 'min' ],
        [ Sequelize.fn('MAX', Sequelize.col('price')), 'max' ],
    ]
});

However, I don't know how to to nest MIN and IF functions, the way I do with raw SQL. 但是,我不知道如何嵌套MINIF函数,就像我处理原始SQL一样。

After posted my question I found an issue in GitHub with a similar problem. 发布我的问题后,我在GitHub中发现了一个类似问题。

The solution I got is the following: 我得到的解决方案如下:

product.findOne({
    attributes: [
        [ Sequelize.fn('MIN', Sequelize.fn('IF',
                Sequelize.literal('`price_special` > 0'),
                Sequelize.col('price_special'),
                Sequelize.col('price'))), 'min' ],
        [ Sequelize.fn('MAX', Sequelize.fn('IF', 
                Sequelize.literal('`price_special` > 0'), 
                Sequelize.col('price_special'), 
                Sequelize.col('price'))), 'max' ],
    ]
});

I personally don't like the Sequelize.literal call, but it's working and I don't know how to improve it. 我个人不喜欢Sequelize.literal电话,但是它正在工作,我也不知道如何改进它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM