【问题标题】:How to combine multiple queries in single in Sequalize, Mysql, Node如何在 Sequelize、Mysql、Node 中合并多个查询
【发布时间】:2021-01-27 22:55:01
【问题描述】:

我想根据类型获取 4 种类型的计数,因为我有 4 个单独的查询,但我只想使用一个查询来一次获取所有 4 个计数。

查询 1:

SELECT count(*) as totalCount FROM orders INNER JOIN order_view ON orders.id= order_view.id 
WHERE order_view.order_type = 'Type1'

查询 2:

SELECT count(*) as totalCount FROM orders INNER JOIN order_view ON orders.id= order_view.id 
WHERE order_view.order_type = 'Type2'

查询 3:

SELECT count(*) as totalCount FROM orders INNER JOIN order_view ON orders.id= order_view.id 
WHERE order_view.order_type = 'Type3'

查询 4:

SELECT count(*) as totalCount FROM orders INNER JOIN order_view ON orders.id= order_view.id 
WHERE order_view.order_type = 'Type4'

我正在通过 Sequelize 查找查询,但似乎找不到任何文档。

【问题讨论】:

    标签: mysql sql node.js count pivot


    【解决方案1】:

    使用条件聚合:

    select 
        sum(ov.order_type = 'type1') as totalcount1,
        sum(ov.order_type = 'type2') as totalcount2
        sum(ov.order_type = 'type3') as totalcount3
        sum(ov.order_type = 'type4') as totalcount4
    from orders o
    inner join order_view on o.id = ov.id 
    where ov.order_type in ('type1', 'type2', 'type3', 'type4')
    

    目前还不清楚为什么在查询中需要表orders。这可能只是你想要的:

    select 
        sum(ov.order_type = 'type1') as totalcount1,
        sum(ov.order_type = 'type2') as totalcount2
        sum(ov.order_type = 'type3') as totalcount3
        sum(ov.order_type = 'type4') as totalcount4
    from order_view
    where ov.order_type in ('type1', 'type2', 'type3', 'type4')
    

    【讨论】:

    • 其实查询量很大,为了更好的理解,我把它剪掉了
    猜你喜欢
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 2015-08-30
    • 2015-08-06
    相关资源
    最近更新 更多