sql - 没有 UNION 的库存 SQL 查询?

标签 sql ruby-on-rails sqlite activerecord

我正在设计一个库存系统,它有用户产品buy_leads订单(授权购买线索)、输入输出

class Product < ActiveRecord::Base
  has_many :buy_leads
end

class BuyLead < ActiveRecord::Base
  belongs_to :product
  has_one :order
end

class Order < ActiveRecord::Base
  belongs_to :buy_lead
  belongs_to :user, :foreign_key => :authorized_by
  has_many :inputs
end

class Input < ActiveRecord::Base
  belongs_to :order
  has_many :outputs
end

class Output < ActiveRecord::Base
  # Associations
  belongs_to :input
  belongs_to :user
end

输入和输出有一个数量值。为了获得产品库存特定产品库存,我在两个原始 SQL 查询中使用 UNION,通过使输出数量为负数,然后分组和将它们加在一起:

class InventoryController < ApplicationController

  def index
    @inventory = Input.find_by_sql products_inventory_sql
  end

  def show
    @inventory = Input.find_by_sql product_inventory_sql(params[:id])
  end

private

  def inputs_sql
    "SELECT b.*, p.*, i.order_id,
            i.id AS input_id,
            i.quantity AS quantity     
     FROM inputs i
          JOIN orders r ON r.id = i.order_id
          JOIN buy_leads b ON b.id = r.buy_lead_id
          JOIN products p ON p.id = b.product_id"
  end

  def outputs_sql
    "SELECT b.*, p.*, i.order_id,
            i.id AS input_id,
            (o.quantity * -1) AS quantity
     FROM outputs o
          JOIN inputs i ON i.id = o.input_id
          JOIN orders r ON r.id = i.order_id
          JOIN buy_leads b ON b.id = r.buy_lead_id
          JOIN products p ON p.id = b.product_id"
  end

  def products_inventory_sql
    "SELECT *, SUM(quantity) AS remaining_qty
     FROM (#{inputs_sql} UNION #{outputs_sql})
     GROUP BY product_id"
  end

  def product_inventory_sql(id)
    "SELECT *, SUM(quantity) AS remaining_qty
     FROM (#{inputs_sql} UNION #{outputs_sql})
     WHERE product_id = #{id}
     GROUP BY order_id, input_id"
  end

end

它有效,但我想使用 named_scope 的特性在 ActiveRecord 中链接查询并能够执行以下操作:

Product.inputs.by_product(id)
Product.inventory.by_product(id)
...

任何想法,或者我是否必须更改模式以获得更方便的模式?谢谢!

最佳答案

解决这个问题的可能性太多了,你到底想从这些报告中得到什么?

买单?产品?输入/输出?

(我将此作为答案发布,因为我无法对您的问题发表评论,如果您能启发我,我会更新答案)

更新

试试这个

#on input
named_scope :by_product, lambda {|id| {:joins => {:orders => {:buy_leads => :products}}, :conditions => ['products.id = ?', id]}}

您可以通过调用获取与该产品 ID 匹配的输入

Input.by_product(25)

如果那是您正在寻找的,我认为您现在也可以设法按产品进行输出:]

关于sql - 没有 UNION 的库存 SQL 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3137224/

相关文章:

sql - 根据地区获取时区

sql - 获取最高价格商品的 ID

sql - 缺少日期的 PostgreSQL 聚合

sql - 我应该如何处理 "forget this"功能背后的数据库逻辑?

ruby-on-rails - ruby rails : Using Parsely-Rails

java - SQLiteDatabase 添加日期到数据库

mysql - 需要用两个不同的 where 子句返回两组数据

ruby-on-rails - 查找具有不同关系的记录 [多对多]

javascript - 是否可以在 Adob​​e AIR 中使用 localStorage 和 window.openDatabase?

python sqlite3 从 excel 创建数据库