SQL:插入...值..选择

2022-01-09 00:00:00 sql insert sql-server

如果我从 TableX 中获取 colA、从 TableY 中获取 colB 以及从 TableZ 中获取 colC 的值,我该如何编写 INSERT 语句?

How do i write INSERT statement if i get the values of colA from TableX, colB from TableY and colC from TableZ?

例如:INSERT INTO TableA (colA, colB, colC) VALUES (?,?,?)

eg: INSERT INTO TableA (colA, colB, colC) VALUES (?,?,?)

如果可能的话,有什么想法吗?

Any ideas if it is possible?

推荐答案

INSERT INTO TableA(colA, colB, colC)
  SELECT TableX.valA, TableY.valB, TableZ.valC
    FROM TableX
   INNER JOIN TableY ON :......
   INNER JOIN TableZ ON ........

当然,TableX、TableY 和 TAbleZ 也可能以其他方式相关(不是 INNER JOIN).

Of course, TableX, TableY and TAbleZ might also be related in some other way (not INNER JOIN).

如果你根本找不到表之间的任何关系,你也可以做三个单独的

If you cannot find any relation between the tables AT ALL, you could also do three separate

SELECT @value1 = valA FROM TableX WHERE ......
SELECT @value2 = valB FROM TableY WHERE ......
SELECT @value3 = valC FROM TableZ WHERE ......

然后是这样的插入:

INSERT INTO TableA(colA, colB, colC)
             VALUES(@value1, @value2, @value3)

这是最后的最后手段,你不能在单个 SELECT 语句中表达所有内容.

That's the ultimate last resort, you can can't express everything in a single SELECT statement.

马克

相关文章