views:

59

answers:

5

Can anyone help me on how can I update one table having a selection to another table in WHERE clause..

My query is looks like this but it is an error..

UPDATE empinfo e SET e.tellno='32154'
 WHERE e.empno IN (SELECT ei.empno FROM empinfo ei WHERE ei.tellno <> '123456');

Your response is highly appreciated.. :)

+3  A: 

why do you need nested query here, try directly

UPDATE empinfo e SET e.tellno='32154'
WHERE e.tellno != '123456'
Chinmayee
+6  A: 

why not:

UPDATE empinfo e SET e.tellno='32154' WHERE tellno <> '123456'
Yannis
+1  A: 

What's wrong with:

UPDATE empinfo e SET e.tellno='32154' WHERE e.tellno <> '123456';

or

UPDATE empinfo e SET e.tellno='32154' WHERE e.tellno != '123456';

or

UPDATE empinfo e SET e.tellno='32154' WHERE e.tellno NOT '123456';

? However, if empno is not unique in your table then this SQL won't work like the one you've provided! So, is empno unique or not?

Workshop Alex
empno there is not a unique value.. is my query will work if the empno is a unique value?
Zen
Doesn't matter if empno is unique or not.
Workshop Alex
A: 

Not sure why I'm answering this as you acceptence rate is rubbish but here goes.

Try this

UPDATE empinfo SET tellno='32154'
WHERE empno IN (
     SELECT empno 
     FROM empinfo 
     WHERE tellno NOT '123456'
);
Ash Burlaczenko
You can't use a select subquery from the same table that is being updated in a where clause.
Eran Galperin
@Eran - You can but not like that. You need to wrap the whole sub query up [as a derived table](http://www.xaprb.com/blog/2006/06/23/how-to-select-from-an-update-target-in-mysql/).
Martin Smith
@Martin Interesting!
Eran Galperin
is it possible to do when you are UPDATING one table then you are going to SELECT on the same table for the WHERE clause of UPDATE query?
Zen
A: 

Okay, example:

REC1: empno=1 tellno='654321'
REC2: empno=2 tellno='654321'
REC3: empno=3 tellno='123456'
REC4: **empno=1** tellno='123456'

When you use something like

UPDATE empinfo e SET e.tellno='32154' WHERE e.tellno != '123456';

Then you will get this:

REC1: empno=1 tellno='32154'
REC2: empno=2 tellno='32154'
REC3: empno=3 tellno='123456'
**REC4: empno=1 tellno='123456'**

However, your original query seems to want to change it to this:

REC1: empno=1 tellno='32154'
REC2: empno=2 tellno='32154'
REC3: empno=3 tellno='123456'
**REC4: empno=1 tellno='32154'**

Which of these two options did you want? If you want the second one, then you'll need to do a sub-select but a subselect on the same table isn't possible with MySQL.

Workshop Alex