Mysql query - where clause with result of subquery

Mysql query - where clause with result of subquery



i am totally depressed with this query, which i am solving for many hours :(


SELECT m_order.id,
(SELECT SUM(price*amount) FROM m_order_item as item WHERE item.id_order = m_order.id) AS total
FROM `m_order`
WHERE total > 100



It returns Unknown column 'total' in 'where clause' constantly, but in result without this problematic where clause column with name "total" is totally ok and calculated.



Thanks for any help.





See: Why should I provide an MCVE for what seems to me to be a very simple SQL query?
– Strawberry
Aug 24 at 13:31




2 Answers
2



You can't use aliases in WHERE clauses. See the manual. Put it into a HAVING instead:


WHERE


HAVING


SELECT m_order.id,
(SELECT SUM(price*amount) FROM m_order_item as item WHERE item.id_order = m_order.id) AS total
FROM `m_order`
HAVING total > 100





Thanks so much! It works
– czLukasss
Aug 24 at 13:43



Total is a column alias and is not visible for where condition .. where part is evaluated by bd engine before the evaluation of select clause



so you should or repeat the code


SELECT m_order.id,
( SELECT SUM(price*amount)
FROM m_order_item as item
WHERE item.id_order = m_order.id ) AS total
FROM `m_order`
WHERE ( SELECT SUM(price*amount)
FROM m_order_item as item
WHERE item.id_order = m_order.id ) > 100



or try using having
having filter the result of select


SELECT m_order.id,
( SELECT SUM(price*amount)
FROM m_order_item as item
WHERE item.id_order = m_order.id ) AS total
FROM `m_order`
HAVING total > 100






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)