LoginSignup
5
4

More than 5 years have passed since last update.

MySQLで自己結合の更新をする

Posted at

MySQLで自己結合して更新する場合は、このような書き方でうまくいきました。

update table_name t1, table_name t2
set t1.value = t2.value
where t1.id = t2.id;

「達人に学ぶ SQL徹底指南書」の「演習問題2-③:ランキングの更新」は解答のとおりに記述してもMySQLではエラーになります。

エラーになる
UPDATE DistrictProducts2 P1 
SET ranking = (SELECT COUNT(P2. price) + 1 FROM DistrictProducts2 P2 WHERE P1. district = P2. district AND P2. price > P1. price);

このようにランキングの入ったテーブルをサブクエリで作成して、その結果から値を更新すればうまくいきました。

更新できた
update DistrictProducts2 p1, (select p3.district as district, p3.name as name, (select count(p4.price) + 1 from DistrictProducts2 p4 where p3.district = p4.district and p4.price > p3.price) as ranking from DistrictProducts2 p3) p2 
set p1.ranking = p2.ranking where p1.district = p2.district and p1.name = p2.name;

他にいい方法があるかもしれません。

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4