上的库存管理系统的工作,我们有如下表:自连接只返回一个记录
================================================
| orders | order_line_items | product_options |
|--------|-------------------|-----------------|
| id | id | id |
| start | order_id | name |
| end | product_option_id | |
| | quantity | |
| | price | |
| | event_start | |
| | event_end | |
================================================
我试图来计算某一特定日期的库存,所以我需要一个自联接将order_line_items上的数量与具有相同product_option_id的order_line_items中的其他记录数量的SUM进行比较,以及事件开始和结束在某个范围内的位置。
所以,对于一个日期2016年1月20日,我有:
SELECT order_line_items.id, order_line_items.product_option_id, order_line_items.order_id FROM order_line_items
WHERE order_line_items.event_end_date >= '2016-01-20 04:00:00'
AND order_line_items.event_start_date <= '2016-01-21 04:00:00'
AND order_line_items.product_option_id IS NOT NULL;
以上的回报127行
当我尝试做一个自我加入,就像这样:
SELECT
order_line_items.id,
order_line_items.product_option_id,
order_line_items.order_id,
order_line_items.quantity,
other_line_items.other_product_option_id,
other_line_items.other_order_id,
other_line_items.other_quantity,
other_line_items.total
FROM order_line_items
JOIN (
SELECT
id,
product_option_id AS other_product_option_id,
order_id AS other_order_id,
quantity AS other_quantity,
SUM(quantity) total
FROM order_line_items
WHERE order_line_items.event_end_date >= '2016-01-20 04:00:00'
AND order_line_items.event_start_date <= '2016-01-21 04:00:00'
) other_line_items ON order_line_items.product_option_id = other_line_items.other_product_option_id
WHERE order_line_items.event_end_date >= '2016-01-20 04:00:00'
AND order_line_items.event_start_date <= '2016-01-21 04:00:00'
AND order_line_items.product_option_id IS NOT NULL;
它只返回1条记录。正如你在这里看到的:()有相同的product_option_id有很多记录,所以这最后一个查询应该返回很多行
一个建议,你需要重命名第二个表,因为系统可能会混淆,并且不需要第二个地方,因为你在子查询中有一个。 –
谢谢 - 删除第二个让我获得更多记录的地方,但现在所有返回的记录都有相同的product_option_id ..奇怪:https:// goo。gl/itL5bF – Laravelian
好吧,在'join'选项中试试这个,'order_id = other_order_id和production_order_id = other_production_order_id' –