H
H
HeBonpoc2014-09-20 13:12:49
MySQL
HeBonpoc, 2014-09-20 13:12:49

MYSQL: Is it possible to write an update query if the condition has join, count, group by and having?

Request to select product IDs that do not have any images:

select product.id as id, count(product_image.id) as COUNT from product left join product_image on product.id = product_image.product_id group by product.id having count = 0;

How to update these items?
So, of course, it didn’t work, because there are 2 columns in the subquery:
update product set disabled = 1 where id in (select product.id as id, count(product_image.id) as COUNT from product left join product_image on product.id = product_image.product_id group by product.id having count = 0);

Already solved the problem with this query:
UPDATE 
product PRODUCT 
  LEFT JOIN product_image IMAGE 
    ON IMAGE.product_id = PRODUCT.id
    SET PRODUCT.disabled = 1
WHERE
  IMAGE.id is NULL;

But that only worked in this particular case. Next time, join and where may not be enough)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Senkevich, 2014-09-20
@ssenkevich

Can it be like this

UPDATE product SET disabled = 1 WHERE id IN (
    SELECT product.id FROM product LEFT JOIN product_image ON product.id = product_image.product_id GROUP BY product.id HAVING COUNT(product_image.id) = 0);

but better like this:
UPDATE product SET disabled = 1 WHERE NOT EXISTS (SELECT 1 FROM product_image WHERE product_id = product.id)

M
Melkij, 2014-09-20
@melkij

table_reference for update is no different from select.
The same subquery left join (select /**/) as sub on /**/ can get data.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question