Me gustaría hacer algo como esto:
- In table TAGS find a row with name='someName', and remeber it's id
- 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
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:
UPDATE TAGS t1, TAGS t2 SET t1.reference = t2.id WHERE t2.name = 'someName' AND t1.someField = someCondition;
This is a better approach.
Convert your subquery to a join y entonces
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 18.104.22.168, “JOIN Syntax”. Here is an example:
UPDATE items,month SET items.price=month.price WHERE items.id=month.id; 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.