提问者:小点点

如何在single in Sequalize,Mysql,Node中组合多个查询


我想获得基于类型的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'

质疑三:

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

质疑四:

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

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


共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')