DEV Community

d.yoshimitsu
d.yoshimitsu

Posted on

2 1

MySQLでサブクエリを使ってUPDATE

MySQLのリファレンスマニュアルに不吉な事が書いてあったけど、うまくいったのでメモ

You cannot update a table and select from the same table in a subquery.

やりたいこと

住所テーブルに顧客毎の並び順を保証する列を追加したい。
列の初期値として、既存データを並び替えて連番を発行する。

やったこと

UPDATE addresses t1,
    (SELECT 
        t3.id,
            SUM(t3.id >= t4.id) AS no
    FROM
        addresses t3
    INNER JOIN addresses t4 ON t3.user_id = t4.user_id
    GROUP BY t3.id) t2
SET 
    t1.no = t2.no
WHERE
    t1.id = t2.id

Top comments (0)

Create and Manage Features in Your AI Agent

Create and Manage Features in Your AI Agent

With DevCycle's MCP server, your AI agent can create, manage and evaluate feature flags - and you can stay in code and in context. Use it to create/QA features end-to-end with a prompt, or to investigate incidents right from your AI-enabled IDE.

Learn More