CodexBloom - Programming Q&A Platform

MySQL 8.0 - scenarios 1054: Unknown column in subquery while using correlated subquery in SELECT

πŸ‘€ Views: 97 πŸ’¬ Answers: 1 πŸ“… Created: 2025-07-22
mysql sql subquery

I'm working with an behavior when trying to run a correlated subquery in MySQL 8.0... The specific behavior message I'm getting is `behavior 1054 (42S22): Unknown column 'a.value' in 'where clause'`. I have a table `items` and I'm trying to find all items whose `value` is greater than the average value of their category from a related `categories` table. Here’s the relevant schema for both tables: ```sql CREATE TABLE categories ( id INT PRIMARY KEY, name VARCHAR(100) ); CREATE TABLE items ( id INT PRIMARY KEY, category_id INT, value DECIMAL(10, 2), FOREIGN KEY (category_id) REFERENCES categories(id) ); ``` The query I wrote looks like this: ```sql SELECT * FROM items AS a WHERE a.value > ( SELECT AVG(b.value) FROM items AS b WHERE b.category_id = a.category_id ); ``` I thought using a correlated subquery would work, but it seems like MySQL need to recognize `a.value` in the subquery. I've tried rewriting the subquery using a `JOIN` instead, but I ended up with more complications in the query structure. Could anyone suggest why this happens and how to fix it? Is there a better way to accomplish this? I want to adhere to best practices because this is going to be used in a production environment. This issue appeared after updating to Sql latest.