简体   繁体   中英

MYSQL: subquery into a table updated in the main query

I'd like do something like this:

  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?

Thank you

Convert your subquery to a join and then 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 12.2.8.1, “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.

you can do this

    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.


Edit#1 You can avoid the sub-queries altogether -- as taspeotis rightly mentioned , by join ing 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM