多个TABLE SQL上的UPDATE

时间:2017-11-25 12:45:02

标签: sql-server

我希望将名字的注释减少2分:Pardin。

我不知道如何通过更新加入。

以下是我的表格:

CREATE TABLE STUDENT 
(
    Mat VARCHAR(20) PRIMARY KEY,
    Name CHAR(20) NOT NULL,
    Firstname CHAR(20),
    DateNais DATETIME,
    CONSTRAINT NameFirUn UNIQUE (Name, Firstname),
)

CREATE TABLE TEST 
(
    CCode INT,
    Mat VARCHAR(20),
    Note FLOAT DEFAULT 0,
    Edate DATETIME,
    CONSTRAINT CHK_NOTE CHECK (Note BETWEEN 0 AND 20),
    FOREIGN KEY (Mat) REFERENCES STUDENT(Mat),
)

我做到了:

UPDATE TEST E1
JOIN STUDENT E2 on E1.Mat = E2.Mat
SET E1.Note -= 2 
WHERE STUDENT.Nom = 'Pardin'

4 个答案:

答案 0 :(得分:0)

尝试这样(在SQL Server中):

UPDATE T 
SET T.Note = T.Note - 2
FROM TEST T 
INNER JOIN STUDENT E2 on T.Mat = E2.Mat AND E2.Nom = 'Pardin'

答案 1 :(得分:0)

在mysql中

UPDATE TEST 
JOIN STUDENT  on TEST.Mat=STUDENT.Mat  AND STUDENT.Nom = 'Pardin'
SET TEST.Note =  TEST.Note -2  

在sql server

UPDATE TEST 
SET TEST.Note =  TEST.Note -2  
FROM TEST
JOIN STUDENT on TEST.Mat=STUDENT.Mat AND STUDENT.Nom = 'Pardin'

答案 2 :(得分:0)

以下是您如何处理UPDATE

的方法
CREATE TABLE STUDENT (
Mat VARCHAR(20) PRIMARY KEY,
Name CHAR(20) NOT NULL,
Firstname CHAR(20),
DateNais DATETIME,
CONSTRAINT NameFirUn UNIQUE (Name, Firstname)
);

CREATE TABLE TEST (
CCode INT,
Mat VARCHAR(20),
Note FLOAT DEFAULT 0,
Edate DATETIME,
CONSTRAINT CHK_NOTE CHECK (Note BETWEEN 0 AND 20),
FOREIGN KEY (Mat) REFERENCES STUDENT(Mat)
);

INSERT INTO STUDENT VALUES
('SQL-Server', 'Pardin', 'Student1', GetDate()),
('Delphi', 'Pardin', 'Student2', GetDate()),
('French', 'NotPardin', 'Student3', GetDate()); -- Not Pardin here

INSERT INTO TEST VALUES
(1, 'SQL-Server', 13, GetDate()),
(2, 'Delphi', 17, GetDate()),
(3, 'French', 15, GetDate()); -- Not pardin here
-- See your data first
SELECT * 
FROM TEST T JOIN STUDENT S ON T.Mat = S.Mat;
-- Update the data in the TEST table
UPDATE T
SET T.Note = T.Note - 2
FROM Test T JOIN STUDENT S ON T.Mat = S.Mat WHERE S.Name = 'Pardin';
-- See the final results
SELECT * 
FROM TEST T JOIN STUDENT S ON T.Mat = S.Mat;

<强> DEMO

答案 3 :(得分:0)

使用嵌套查询的SQL Server解决方案:

update test
set note -=2
where mat in (select mat from student where Nom='Pardin')

如果子查询完全返回一条记录,则可以将=替换为in