0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MySQL エラー1175対処法 (SAFE UPDATE設定を変更せずにテーブルをUPDATEする方法)

Last updated at Posted at 2025-05-06
-- Show all databases
SHOW DATABASES;

-- Use the specified database
USE db_name;

-- Show all tables in the current database
SHOW TABLES;

-- Show the keys of the specified table
SHOW KEYS FROM table WHERE Key_name = 'PRIMARY';

-- 'instance_id' is assumed to be the PRIMARY key

-- Retrieve the instance_ids as a comma-separated string
SET @instance_ids = (SELECT GROUP_CONCAT(instance_id) FROM instances WHERE name = 'mikhail ');

-- Prepare the UPDATE query dynamically
SET @update_query = CONCAT('UPDATE instances SET name = "mikhail" WHERE instance_id IN (', @instance_ids, ')');

-- Execute the prepared query
PREPARE stmt FROM @update_query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Explanation:

この方法では、SAFE UPDATE設定を変更せずに、UPDATEクエリを実行する方法を示します。通常、SAFE UPDATEが有効になっていると、次のような制限が適用されます:

UPDATE文には、インデックスのある列をWHERE句に含める必要があります。

条件が不明確だと、UPDATEがエラーになります。

しかし、instance_idが主キーとして定義されているため、WHERE句にinstance_idを使用することで、SAFE UPDATEの制限を回避できます。

SHOW KEYS FROM table WHERE Key_name = 'PRIMARY':

まず、テーブルの主キー情報を取得します。instance_idは主キーとして設定されていると仮定しています。

SET @instance_ids = ...:

name = 'mikhail'という条件に一致するインスタンスのinstance_idをカンマ区切りの文字列として取得しています。GROUP_CONCATを使用して、複数のIDを1つの文字列にまとめます。

SET @update_query = CONCAT(...):

取得したinstance_idリストを使って、動的にUPDATEクエリを生成します。CONCAT関数を使って、WHERE instance_id IN (...)という形式でクエリを作成します。

PREPARE stmt FROM @update_query; EXECUTE stmt; DEALLOCATE PREPARE stmt;:

最後に、動的に生成したUPDATEクエリを実行します。PREPARE、EXECUTE、DEALLOCATEは、動的クエリを安全に実行するために使用されます。

なぜSAFE UPDATE設定を変更しないのか?
SAFE UPDATEが有効な場合、UPDATE操作はWHERE句でインデックスを使用している必要があります。ここでは、instance_idが主キーでありインデックスが設定されているため、WHERE句にinstance_idを使うことで、SAFE UPDATEの制限をクリアできます。そのため、SAFE UPDATE設定を変更せずにUPDATEを実行することができます。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?