0

I am new to MySQL statements, so bear with me.

I am working with a single table that contains 3 columns. ID, value, and report ID.

What I am looking to do is update the 'value' to yes of id = 2 WHEN the value is 'yes' for id = 1, and at the same time matching the report id is matching between id 1 and id 2. Apologies if this doesn't make sense, please let me know if I need to clarify better.

Here are some queries I've attempted so far:

UPDATE table
    SET value = CASE WHEN value = 'Yes' AND id = 1 AND report_id LIKE report_id 
THEN 'Yes' ELSE value END
    WHERE (id = 2 or id = 1);

UPDATE table 
SET value = 'Yes'     
WHERE (report_id = report_id     
AND value = 'Yes')     
AND id = 1     
 OR id = 2;

UPDATE table
SET value = IF(value = 'Yes' AND report_id LIKE report_id AND id = 1, 'Yes', '')
WHERE id = 2;

Example Table:

id value report_id
1 yes 1001
1 no 1002
1 yes 1003
2 1001
2 1002
3 cat 1001
5 1002
3
  • report_id LIKE report_id will always be true -- everything is always like itself. What are you trying to do with that? Commented Sep 22, 2022 at 19:51
  • If you're trying to compare report_id between two different rows, you need to join the table with itself. Commented Sep 22, 2022 at 19:53
  • I am trying to compare report_id between two different rows, making sure they are identical. Thank you! Commented Sep 22, 2022 at 20:13

3 Answers 3

1

All your conditions are being processed on a single row, not comparing the id=1 rows to the id=2 rows with the same report_id.

You can use a self-join to compare different rows of the table with a relationship.

You don't need CASE, you can select the rows to update using the WHERE conditions.

UPDATE t1
JOIN t2 ON t1.report_id = t2.report_id
SET t1.value = 'yes'
WHERE t1.id = 2 AND t2.id = 1 AND t2.value = 'yes'
Sign up to request clarification or add additional context in comments.

Comments

1

If I understood correctly, please try to use something like below to get the result. You need to use the same table in exists condition as well. I hope my answer helps you.

update table t set t.value = 'Yes' where exists ( select 1 from table t1 where 
    t1.value = 'Yes' and t1.id = 1 and t.report_id = t1.report_id) and t.id = 2;

Comments

0
UPDATE 
  table a 
  JOIN table b ON a.report_id = b.report_id 
SET 
  a.value = 'Yes' 
WHERE 
  a.id = 2 
  AND b.id = 1 
  AND b.value = 'Yes';

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.