0

I am trying to perform a count query in mysql to update a column (no_of_orders) in my users table using data from another table (orders).

The table I want to perform a query on is the orders table that has a created_date column in datetime format.

I would like to count the number of orders each user has made in the last 3 months.

I have tried the below and I am getting an error "Operand should only contain one column".

UPDATE users u SET no_of_orders = (
SELECT EXTRACT(month from created_date)>= NOW() - INTERVAL 3 MONTH ,
COUNT(*)
FROM orders o
WHERE o.created_by = u.user_id);

Is there a better way to do this?

Thank you!

3
  • You need to look into GROUP BY. That won't solve your problem, but may help. Commented Jul 14, 2022 at 14:39
  • The update is not correct. Move the extract part in the where clause and put same sub-query outside with where exists clause too. Commented Jul 14, 2022 at 14:39
  • The error comes from the select clause, you select 2 data and the update expect only 1 data. You should separate the count and extract. Commented Jul 14, 2022 at 14:40

2 Answers 2

1

LEFT join the table users to a query that aggregates in the table orders:

UPDATE users u 
LEFT JOIN (
  SELECT created_by, COUNT(*) count
  FROM orders
  WHERE created_date >= NOW() - INTERVAL 3 MONTH
  GROUP BY created_by
) o ON o.created_by = u.user_id 
SET u.no_of_orders = COALESCE(o.count, 0);
Sign up to request clarification or add additional context in comments.

4 Comments

hi, thank you but this returns the total number of orders, not ones made in the last 3 months
@lavender1 dis you miss WHERE created_date >= NOW() - INTERVAL 3 MONTH ?
No, I copied your answer exactly
@lavender1 then either you are doing something wrong or created_date is not a valid datetime.
0
UPDATE users u SET no_of_orders = (
SELECT COUNT(*)
FROM orders o
WHERE o.created_by = u.user_id AND  EXTRACT(month from o.created_date)>= NOW() - INTERVAL 3 MONTH ) GROUP BY o.created_by;

In sub-query you are returning more than one column that's why the error

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.