问题
I'm new in Pure Sql I want to write this as 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
but this gives an error
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
i don't know why it's not working
回答1:
The syntax error here is that you need an on
-clause for your left join
. But the underlying conceptual problem is different: you cannot join
with a dependent subquery.
You can fix your query like this:
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;
This moved your inner where
-condition (that would depend on items.id
, which is not allowed, as it is out of scope) to the on
-clause. Thus item_id
is also added in the inner select
(as it is needed outside).
A different way to write this would be
select items.*,
(select sum(purchase_details.quantity)
from purchase_details
where purchase_details.item_id=items.id) as total
from items;
Here you have a dependent subquery: the inner where
-clause depends on the outer items.id
. You do not need a group by
anymore, as the where
-condition already uses just the rows for that item. (And you can also only return at most one row in this context anyway.)
Both queries are equivalent, and can (if the optimizer finds that execution plan) internally actually be executed in exactly the same way (which is nothing you have to care about much though, as long as you provide appropriate indexes).
So in your case you can use both (and maybe check which one is faster); if you want to get additional information for that item, you should prefer the left join
-version though, e.g. use
...
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;
来源:https://stackoverflow.com/questions/45501135/sql-query-on-multiples-tables