3

I have this query

UPDATE trh_adminLoginDate SET superseded = true WHERE EXISTS 
 (SELECT * FROM trh_adminLoginDate AS a2 WHERE a2.adminId = a.adminId AND a2.loginDate > a.loginDate AND a2.clientPlatform = a.clientPlatform)

and table look like this.

+----------------+--------------+------+-----+---------+----------------+
| Field          | Type         | Null | Key | Default | Extra          |
+----------------+--------------+------+-----+---------+----------------+
| id             | bigint(20)   | NO   | PRI | NULL    | auto_increment |
| dateCreated    | datetime     | NO   |     | NULL    |                |
| version        | int(11)      | NO   |     | NULL    |                |
| dateModified   | datetime     | NO   |     | NULL    |                |
| adminId        | bigint(20)   | NO   | MUL | NULL    |                |
| clientPlatform | varchar(255) | YES  |     | NULL    |                |
| loginDate      | datetime     | YES  |     | NULL    |                |
| superseded     | tinyint(1)   | NO   |     | NULL    |                |
+----------------+--------------+------+-----+---------+----------------+

When I execute this query I get the below error:

ERROR 1093 (HY000): You can't specify target table 'a' for update in FROM clause

I can create temporary table and keep the result of the sub-query and then do the UPDATE. But I don't want to do in this way. Can someone suggest me better way of doing this?

Rakesh
  • 3,987
  • 10
  • 43
  • 68

2 Answers2

4

You are using the alias "a" but you never define it.

Perhaps this would work:

UPDATE  trh_adminLoginDate a

        JOIN trh_adminLoginDate AS a2 
        ON a2.adminId = a.adminId 
        AND a2.loginDate > a.loginDate 
        AND a2.clientPlatform = a.clientPlatform

SET a.superseded = true
Tom
  • 6,593
  • 3
  • 21
  • 42
-1

Or perhaps this will do the trick:

UPDATE trh_adminLoginDate a

SET    superseded = true 

WHERE EXISTS 
      (SELECT * FROM trh_adminLoginDate WHERE adminId = a.adminId AND loginDate > a.loginDate AND clientPlatform = a.clientPlatform)
Tom
  • 6,593
  • 3
  • 21
  • 42
  • This query works for SQL but doesn't work on the HQL. Can you please provide me the HQL version? – Rakesh Nov 02 '12 at 02:57