1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【MySQL】複数テーブルをJOINしてUPDATEする

Posted at

はじめに

複数テーブルをJOINしてUPDATEする機会がたまにあるのですが、毎回ググってるので簡単にまとめておきます。

構文

UPDATE tableA AS t1
JOIN tableB AS t2 ON (t1.columnA = t2.columnB)
SET 
    columnC = value,
    columnD = value,
WHERE t1.columnA = value;

JOINの後にSETを書きます。

具体例

社員(employees)テーブルと部署(departments)テーブルがあるとします。

ER図

Mermaid記法
mermaid.md
erDiagram
    departments ||--o{ employees : "1つの部署には0人以上の社員がいる"
    departments {
        int id PK
        varchar(3) code
        varchar(100) name
    }
    employees {
        int id PK
        varchar(3) department_code FK
        varchar(100) name
        int salary
    }
CREATE文
create.sql
CREATE TABLE departments
(	id integer PRIMARY KEY,
	code varchar(3) NOT NULL,
	name varchar(100) NOT NULL
);

CREATE TABLE employees
(
	id integer PRIMARY KEY, 
	department_code varchar(3),
	name varchar(100) NOT NULL,
	salary integer,
	FOREIGN KEY(department_code)
	REFERENCES departments(code)
);
INSERT文
insert.sql
INSERT INTO departments
(id, code, name)
VALUES
(1, "001", "人事部"),
(2, "002", "開発部");

INSERT INTO employees
(id, department_code, name, salary) 
VALUES
(1, "001", "鈴木太郎", 300000),
(2, "001", "田中次郎", 250000),
(3, "002", "渡辺花子", 400000),
(4, "002", "佐藤洋子", 150000);

UPDATE文

部署名が"開発部"の人だけ給料を20%増にします。

update.sql
UPDATE employees AS t1
JOIN departments AS t2 ON (t1.department_code = t2.code)
SET t1.salary = t1.salary * 1.2
WHERE t2.name = "開発部"
;

WHERE句は使用せずにON句で条件を指定することも可能です。

update.sql
UPDATE employees AS t1
JOIN departments AS t2 ON (t1.department_code = t2.code AND t2.name = "開発部")
SET t1.salary = t1.salary * 1.2
;

おわりに

はじめてMermaid記法を使いましたが、簡単にER図を書けて便利でした。

参考

Mermaid記法について

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?