[英]Error Code 1054 unknown column on cross join
I have three tables item
, store
and stock_movement
. 我有三个表
item
store
和stock_movement
。 The stock movement has the fields id
, item_id
, store_id
and quantity
. 库存移动具有字段
id
, item_id
, store_id
和quantity
。 I would like to create a view showing the sum of the quantities of each item in each store. 我想创建一个视图,显示每个商店中每个项目的数量总和。 If there is no
stock_movement
entry for an item in a store, the quantity should be zero. 如果商店中没有
stock_movement
条目,则数量应为零。
I came up with the following query: 我想出了以下查询:
SELECT item.*, store.id, SUM(s.quantity) AS quantity
FROM item, store
LEFT JOIN stock_movement s ON s.item_id = item.id AND store.id = s.store_id
GROUP BY store.id, item.id;
I get the following error: 我收到以下错误:
Error Code: 1054 Unknown column 'item.id' in 'on clause'
错误代码:1054“ on子句”中的未知列“ item.id”
If I switch the query to use FROM store, item
the unknown column changes: 如果我将查询切换为使用
FROM store, item
则未知列的FROM store, item
将更改:
Error Code: 1054 Unknown column 'store.id' in 'on clause'
错误代码:1054“ on子句”中的未知列“ store.id”
This answer to use INNER JOIN
won't work for me since there are some items and stores without corresponding stock_movement
entries ie the result is missing a few rows. 使用
INNER JOIN
答案对我不起作用,因为有些商品和商店没有相应的stock_movement
条目,即结果缺少几行。
So is there a way to do this cross join? 那么有没有办法进行这种交叉联接?
You need to explicitly define your cross join
: 您需要明确定义
cross join
:
select i.id, s.id, coalesce(sum(si.quantity),0) quantity
from store s
cross join item i
left join storeitem si on s.id = si.storeid and i.id = si.itemid
group by i.id, s.id
BTW -- by doing it this way, you are creating a cartesian product -- all stores have all items. 顺便说一句-通过这种方式,您正在创建笛卡尔产品-所有商店都有所有商品。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.