从多个表插入,多行

时间:2019-05-06 12:58:24

标签: sql oracle

我一直在尝试解决我的问题,但是找不到答案。 Oracle数据库。

我有一个表 context ,其外观如下:

| contextId | customer |
 ----------------------
|         1 | John     |
|         2 | David    |

我还有另一个表 setting

| contextId | settingName | settingValue |
 ----------------------------------------
|         1 | Happiness   |            6 |
|         1 | Sadness     |            3 |

我想在复制 settingName settingValue 约翰(contextId = 1)的同时,在 setting 中插入David。 / p>

结果应如下所示:

| contextId | settingName | settingValue |
 ----------------------------------------
|         1 | Happiness   |            6 |
|         1 | Sadness     |            3 |
|         2 | Happiness   |            6 |
|         2 | Sadness     |            3 |

谢谢

3 个答案:

答案 0 :(得分:5)

INSERT INTO SETTING
  SELECT (SELECT CONTEXTID FROM CONTEXT WHERE CUSTOMER = 'DAVID'),
         SETTINGNAME,
         SETTINGVALUE
    FROM SETTING
   WHERE CONTEXTID = 1

答案 1 :(得分:1)

如果您的要求是使用客户名称“ David”和“ John”,那么您需要加入:

INSERT INTO SETTING (CONTEXTID, SETTINGNAME, SETTINGVALUE)
  SELECT 
    (SELECT CONTEXTID FROM CONTEXT WHERE CUSTOMER = 'David'),
    s.SETTINGNAME,
    s.SETTINGVALUE
  FROM CONTEXT AS c INNER JOIN SETTING AS s 
  ON s.CONTEXTID = c.CONTEXTID
  WHERE c.CUSTOMER = 'John'

答案 2 :(得分:0)

声明了一个单独的变量来保存contextId中的customer - David。然后在setting表中插入customer - David可用的多个值。

DECLARE
  l_contextId context.contextId%TYPE;
BEGIN

  SELECT
    contextId
  INTO
    l_contextId
  FROM
    context
  WHERE
    customer = 'David';

END; 


INSERT INTO setting
(contextId, settingName, settingValue)
SELECT l_contextId, settingName, settingValue
FROM setting
WHERE contextId = 1