Sql-Server

SQL INSERT INTO SELECT 查詢用於更新同一張表並進行一些修改

  • January 21, 2021

我想更新這張表

Table name: Student

Name      Department

Alex         CSE
Bob          EEE
Briyan       ME

通過複製所有行並進行一些修改,如下表:

Table name: Student

Name      Department

Alex         CSE
Bob          EEE
Briyan       ME
Mr. Alex     SCIENCE(CSE)
Mr. Bob      SCIENCE(EEE)
Mr. Briyan   SCIENCE(ME)

SQL查詢應該是什麼……你能幫忙嗎?

到目前為止,我已經嘗試過了:

INSERT INTO 
   Student (Name, Department)
SELECT Name,Department FROM Student;

所以你已經接近了,你只需要將你想要的數據修改添加到SELECT列表中的每個欄位,如下所示:

INSERT INTO 
   Student (Name, Department)
SELECT CONCAT('Mr. ', Name), CONCAT('SCIENCE(', Department, ')') FROM Student;

您可以使用該CONCAT()函式在 MySQL 中連接字元串

強烈建議您要這樣做。

您試圖將多位資訊儲存到單個欄位中,這破壞了關係數據庫設計的最基本原則之一 - 原子性。數據庫非常擅長查找少量數據並將它們組合在一起。他們真的擅長找到大量資訊並將它們分開。

“亞歷克斯先生”是兩個資訊——這個人的頭銜和他們的名字。這些應保存在單獨的欄位中。

為什麼?因為每個都可以獨立於另一個更改,並且將它們放在不同的欄位中,這真的很容易做到。

“SCIENCE(CSE)”也是兩個資訊——不知道你用什麼名字來描述它們,但我要和教職員工一起去。

你的表應該看起來更像這樣:

/* Assuming that a Student can only be part of *one* Department: */ 

select * from Student ; 

+-------+----------+-----------+
| title | forename | dept_code | 
+-------+----------+-----------+
| Mr.   | Alex     | CSE       |
| Mr.   | Bob      | EEE       |
| Mr.   | Briyan   | ME        |
+-------+----------+-----------+

/* You need data about each Department */

select * from Department ; 

+------+-------------+
| code | name        | ... 
+------+-------------+
| CSE  | Comp.Sci.   | ... 
| EEE  | Engineering | ... 
| ME   | Math        | ... 
+------+-------------+

/* You need to know which Faculty each Department belongs to */ 

select * from FacultyDepartment ; 

+----------+-----------+
| fac_code | dept_code | 
+----------+-----------+
| SCIENCE  | CSE       | 
| SCIENCE  | EEE       | 
| SCIENCE  | ME        | 
+----------+-----------+

/* You need data about each Faculty */ 

select * from Faculty ; 

+---------+---------+ 
| code    | name    | ... 
+---------+---------+ 
| SCIENCE | Science | ... 
+---------+---------+ 

所以(最後)建構你想要的數據:

select 
 s.title || ' ' || s.forename name 
, df.dept_code || '(' || df.faculty_code || ')' dept 
from Students s
inner join DepartmentFaculty df 
     on   s.dept_code = df.dept_code 
order by 1, 2 ; 

+------------+--------------+
| name       | department   |
+------------+--------------+
| Mr. Alex   | SCIENCE(CSE) | 
| Mr. Bob    | SCIENCE(EEE) | 
| Mr. Briyan | SCIENCE(ME)  | 
+------------+--------------+

引用自:https://dba.stackexchange.com/questions/283687