复杂的SQL postgres查询到ActiveRecord表示法?

时间:2017-05-21 20:54:57

标签: sql ruby-on-rails postgresql activerecord

希望 ActiveRecord 向导可以帮助我确定是否可以使用AR语句完成此类查询,即不执行原始SQL或潜入Arel?

我已经接近但似乎无法弄清楚如何添加子查询。我在 Rails 5.1.1

HashTableEntry *util = NULL;
util = realloc(util, sizeof(HashTableEntry) * T->capacity);

最终结果应该是库存ID为6的所有库存,其他列显示对它们进行的调整(如果存在)。

如果我在Navicat中运行RAW SQL,我会得到这个结果,这是我想通过ActiveRecord获得的结果:enter image description here

这让我很接近,但它只产生了stock_ids 11和10:

SELECT s.id as stock_id, s.count, adjustments.count as 
adjustment_count, adjustments.reason as adjustment_reason
FROM 
(SELECT * FROM stocks WHERE inventory_id = 6) AS s
LEFT JOIN adjustments 
ON (s.id = adjustments.stock_id AND adjustments.reason='run_use')

2 个答案:

答案 0 :(得分:0)

嗯。你好像在试图说:

  

给我所有属于库存的ID = 6的库存,其中还有调整,其原因是'运行使用'。

如下:

Stock.
  where(inventory_id: 6).
  joins(:adjustments).
  where(adjustments: { reason: 'run_use' })
来自Guides

答案 1 :(得分:0)

其中一个适合你:

Stock.eager_load(:adjustments)
  .where("adjustments.reason = ? OR stocks.inventory_id = ?", "run_use", 6)

Stock.eager_load(:adjustments)
  .where(adjustments: { reason: "run_use" }, inventory_id = 6)