带有计数的子选择

时间:2019-01-22 13:19:24

标签: mysql node.js sequelize.js

我有一个SQL查询,我想用sequelize代码编写。它是一个选择,嵌套有一个选择计数。有人可以帮我存档吗?

我希望这个原始查询能够与sequelize中的nodejs一起使用,但是我不想使用原始查询。

最后应该是这样的:

{product: [included product model], stock count: 5}

SELECT 
  products.id as 'ID', 
  (SELECT COUNT(*) 
   from stocks 
   WHERE stocks.fk_product = products.id 
     AND stocks.sold = 0) AS 'counts' 
FROM products

我真的不知道该怎么做...

1 个答案:

答案 0 :(得分:0)

SELECT COUNT(*) as `count`, s.fk_product as `ID` from stocks as s WHERE s.sold = 0 group by s.fk_product