我是Pure Sql的新手我想把它写成Query
select items.*
from items
LEFT OUTER JOIN
(select sum(purchase_details.quantity) as total
from purchase_details
where (purchase_details.item_id=items.id)
GROUP BY purchase_details.item_id) ABC
但这会产生错误
You have an error in your SQL syntax; check the manual that corresponds to
your MariaDB server version for the right syntax to use near 'LIMIT 0, 25'
at line 1
我不知道为什么它不能正常工作
答案 0 :(得分:0)
此处的语法错误是您需要on
- left join
条款。但是潜在的概念问题是不同的:你不能join
使用依赖子查询。
您可以像这样修复查询:
select items.*
from items
LEFT OUTER JOIN (
select item_id, sum(purchase_details.quantity) as total
from purchase_details
GROUP BY purchase_details.item_id
) ABC on ABC.item_id = items.id;
这会移动你的内部where
- 条件(这将取决于items.id
,这是不允许的,因为它超出范围)到on
- 子句。因此item_id
也会添加到内部select
中(因为外部需要)。
另一种写这个的方法是
select items.*,
(select sum(purchase_details.quantity)
from purchase_details
where purchase_details.item_id=items.id) as total
from items;
这里有一个依赖子查询:内部where
- 子句取决于外部items.id
。您不再需要group by
,因为where
条件已经只使用该项的行。 (而且你也可以在这种情况下最多返回一行。)
两个查询都是等价的,并且可以(如果优化器发现执行计划)内部实际上以完全相同的方式执行(只要您提供适当的索引,这是您不必关心的事情)。 / p>
所以在你的情况下,你可以使用两者(也许检查哪一个更快);如果您想获得该项目的其他信息,您应该更喜欢left join
- 版本,例如使用
...
LEFT OUTER JOIN (
select item_id,
sum(purchase_details.quantity) as total,
count(purchase_details.item_id) as cnt,
max(purchase_details.quantity) as max_quantity_per_order,
max(purchase_details.date) as latest_order,
...
from purchase_details
GROUP BY purchase_details.item_id
) ABC on ABC.item_id = items.id;