0

I didn't know how to clearly title this.

After joining a table on itself using shared_id I get the following data.

a.id   | a.shared_id | a.key     | a.value         | b.id   | b.shared_id | b.key       | b.value
198131 | 6044        | unique-id | E15SJOEMGRMH013 | 198281 |6044         | _unique_id  |

This is the result from:

SELECT * FROM
(SELECT * FROM table1 WHERE key='unique-id') AS a
JOIN
(SELECT * FROM table1 WHERE key='_unique_id') AS b
ON a.shared_id = b.shared_id
WHERE a.value!='' AND a.value!=b.value AND a.key='unique-id'
;

What I need is an update statement that will set b.value to a.values value.So in this 1 row example I want b.value to be E15SJOEMGRMH013.

Now remember a.id and b.id are NOT the same as the keys are called something slightly different but they should hold the same value. There are several hundred rows so I would like to do this in one update query.

2
  • 1
    Please show what you tried. You basically take your join, replace the SELECT <columns> FROM <tablename> b with UPDATE <tablename> , and add SET b.value = a.value at the end. Commented Feb 5, 2015 at 19:24
  • @Barmar query added. im not sure how to make it an update statement because of the multiple rows with different ids and yet the same shared_id. Commented Feb 5, 2015 at 19:29

1 Answer 1

2

You don't need the sub-queries, and your use of them is probably why you couldn't figure out the corresponding UPDATE query.

UPDATE table1 AS a
JOIN table1 AS b ON a.shared_id = b.shared_id
SET b.value = a.value
WHERE a.key = 'unique-id' AND b.key = '_unique_id'
    AND a.value != ''

The SELECT should be simply:

SELECT *
FROM table1 AS a
JOIN table1 AS b ON a.shared_id = b.shared_id AND a.value != b.value
WHERE a.key = 'unique-id' AND b.key = '_unique_id'
    AND a.value != ''

You don't need the a.value != b.value clause in the UPDATE -- if they're the same, the UPDATE doesn't do anything.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow yes this is much easier then the way I built it out I see my logic error now. Thanks!

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.