将具有相同字段的3个表中的数据插入到1个表中

时间:2015-06-10 11:34:31

标签: mysql sql insert insert-into

我有3个表(accntjobcostservic15)。所有字段都相同(codejnovendate)。我需要在一个查询中将这些表中的数据插入到另一个名为dummy的表中,该表具有相同的字段。我该怎么做?

我使用了3个单独的插入到如下所示的语句中:但我需要在一个语句中使用它:

INSERT INTO dbo.dummy
SELECT
dbo.jobcost.code,
dbo.jobcost.ven,
dbo.jobcost.date,
dbo.jobcost.jno,
FROM 
dbo.jobcost
WHERE
dbo.jobcost.jno > '40000'
INSERT INTO dbo.dummy
SELECT
dbo.servic15.code,
dbo.servic15.ven,
dbo.servic15.date,
dbo.servic15.jno
FROM 
dbo.servic15
WHERE

dbo.servic15.jno > '40000'

INSERT INTO dbo.dummy
SELECT
dbo.accnt.code,
dbo.accnt.ven,
dbo.accnt.date,
dbo.accnt.jno
FROM 
dbo.accnt
WHERE
dbo.jobcost.jno > '40000'

2 个答案:

答案 0 :(得分:3)

您需要INSERT ... SELECT声明

INSERT INTO dummy  (code, jno, ven, date)
  SELECT code, jno, ven, date FROM accnt jno > '40000'
  UNION ALL
  SELECT code, jno, ven, date FROM jobcost jno > '40000'
  UNION ALL
  SELECT code, jno, ven, date FROM servic15 jno > '40000';

如果尚未创建表格,请使用CREATE TABLE ... SELECT

答案 1 :(得分:0)

INSERT INTO dummy  (code, invno, ven, invdate, amon, accno, amnt, jno, saccno, ckno)
  SELECT code, invno, ven, invdate, amon, accno, amnt, jno, saccno, ckno FROM accnt 
  WHERE jno > '40000'
  UNION ALL
  SELECT code, invno, ven, invdate, amon, accno, amnt, jno, saccno, ckno FROM jobcost 
  WHERE jno > '40000'
  UNION ALL
  SELECT code, invno, ven, invdate, amon, accno, amnt, jno, saccno, ckno FROM servic15 
  WHERE jno > '40000';

这很有用