如何在MySQL中使用合并功能?

时间:2014-05-13 12:25:14

标签: mysql sql

我还是sql查询的新手。

我的表格查询如下:

CREATE TABLE Department (
    D#      NUMBER(5)   NOT NULL, /* Department number      */
    DName       VARCHAR2(30)    NOT NULL, /* Department name        */
    Manager#    CHAR(5)     NOT NULL, /* Department manager number  */
    MSDate      DATE,             /* Manager start date         */
    CONSTRAINT Department_PK PRIMARY KEY(D#),
    CONSTRAINT Department_CK UNIQUE(DName)
);
INSERT INTO Department VALUES (1, 'SALES', '00110', TO_DATE('02/01/2012', 'DD/MM/YYYY'));
INSERT INTO Department VALUES (2, 'ACCOUNTING', '00120', TO_DATE('30/10/2010', 'DD/MM/YYYY'));
INSERT INTO Department VALUES (3, 'GAMES', '00150', TO_DATE('01/03/2008', 'DD/MM/YYYY'));
INSERT INTO Department VALUES (4, 'HUMAN RESOURCES', '00200', TO_DATE('02/01/2013', 'DD/MM/YYYY'));
INSERT INTO Department VALUES (5, 'SPORTS', '00250', TO_DATE('10/05/2010', 'DD/MM/YYYY'));

我要实现sql查询,就像部门“SPORTS”将合并到部门“GAMES”。部门经理“GAMES”仍然是该部门的经理。在“SPORTS”部门工作的员工住在同一地点。

MERGE INTO department d
USING (
  SELECT Manager#,MSDate
  FROM department d
ON (d.D# = 'GAMES')
WHEN MATCHED THEN
  UPDATE SET d.Manager# = d.Manager#
WHEN NOT MATCHED THEN
  ...

*

不知怎的,我曾尝试使用此查询尝试但没有运气它没有工作:(我非常感谢帮助,如果有的话。

2 个答案:

答案 0 :(得分:1)

MySql不支持MERGE

查看INSERT ... ON DUPLICATE KEY UPDATE Syntax

  

如果指定ON DUPLICATE KEY UPDATE,则插入一行   会在UNIQUE索引或PRIMARY KEY,MySQL中导致重复值   执行旧行的UPDATE

答案 1 :(得分:0)

在MySql上不存在合并命令,但是您可以像这样使用ON DUPLICATE KEY UPDATE:

INSERT INTO table(col_a, col_b) values ('valueA', 'valueB')
ON DUPLICATE KEY
UPDATE col_a = 'valueD', col_b = 'ValueE';