MYSQL: subconsulta en una tabla actualizada en la consulta principal

Me gustaría hacer algo como esto:

  1. In table TAGS find a row with name='someName', and remeber it's id
  2. In the same table find another row with someCondition and set in this row col refference=the id from above

Tried to do this using a subquery, but mysql refused saying I can't subquery a table that I'm updating in the main query.

How can I otherwise implement the above idea?


preguntado el 08 de enero de 11 a las 22:01

2 Respuestas

Puedes hacerlo

    update TAGS set 
    reference = 
        (select my_id from 
            (select id as my_id from TAGS where name='someName') 
         as SUB_TAGS) 
    where someCondition;

Not advisable though.

Editar # 1 You can avoid the sub-queries altogether -- as taspeotis rightly mentioned, por joining the same table with the criteria. Here goes the code for that:

    TAGS t1, TAGS t2 
    t1.reference =
  WHERE = 'someName' 
        t1.someField = someCondition;

This is a better approach.

contestado el 23 de mayo de 17 a las 15:05

I guess the double nesting to workaround the very issue that mysql reported me? and why not advisable? - shealtiel

Use of temporary table is not advisable -- and that's what exactly I am doing here. Temp tables has unnecessary overhead. - Nishant

@gidireich wow, was my tribal knowledge wrong? I do not see much articles on performance overhead of temp tables in mySQL while Googling around. - Nishant

@gidireich well someone suggest to avoid nested queries :)… But this is pretty much "the" solution as you wanted. - Nishant

This worked, thank you. Can you explain what was the problem and cómo what you proposed solved it? - shealtiel

Convert your subquery to a join y entonces UPDATE:

You can also perform UPDATE operations covering multiple tables. However, you cannot use ORDER BY or LIMIT with a multiple-table UPDATE. The table_references clause lists the tables involved in the join. Its syntax is described in Section, “JOIN Syntax”. Here is an example:

UPDATE items,month SET items.price=month.price
The preceding example shows an inner join that uses the comma operator, but multiple-table 

UPDATE statements can use any type of join permitted in SELECT statements, such as LEFT JOIN.

Respondido el 09 de enero de 11 a las 01:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.