简体   繁体   中英

How to nest SQL functions in sequelize.js?

I'm using Sequelize.JS to connect to a MySQL database. 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). With raw SQL, I can do the following:

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:

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.

After posted my question I found an issue in GitHub with a similar problem.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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