SQL插入多个选择

时间:2019-03-28 18:59:40

标签: sql sql-server

我正在尝试进行查询,我想在此表中插入一些具有指定条件的选择中的数据。

 INSERT INTO concediati (nume, prenume, idclient, idrent, idcar) 
 VALUES
     ((SELECT clients.Firstname FROM clients WHERE id = 1),
      (SELECT clients.lastname FROM clients WHERE id = 1), 
      (SELECT clients.id FROM clients WHERE idteam = 1), 
      (SELECT rentcar.id FROM rentcar WHERE idteam = 1), 
      (SELECT cars.id FROM cars WHERE idteam = 1) 
     );

此查询的问题是它引发了错误:

  

“子查询返回多个值。当子查询跟随=,<,<=,>或用作表达式时,不允许这样做。”

我尝试执行此交叉联接查询..但是它超越了我..我不知道该怎么做或该怎么做。

之所以这样做,是因为我想“解雇”一名员工,然后将所有数据发送到表或分配给另一名员工。

2 个答案:

答案 0 :(得分:2)

您可以JOIN 3张桌子。

INSERT INTO concediati (nume, prenume, idclient, idrent, idcar) 
SELECT c.FirstName, c.LastName, c.id, rc.id, ca.id
FROM clients c
JOIN rentcar rc ON rc.idteam = c.id
JOIN cars ca ON ca.idteam = c.id
WHERE c.id = 1

JOIN

上添加条件
INSERT INTO concediati (nume, prenume, idclient, idrent, idcar) 
SELECT c.FirstName, c.LastName, c.id, rc.id, ca.id
FROM clients c
JOIN cars ca ON ca.idteam = c.id
JOIN rentcar rc ON rc.idteam = c.id AND rc.cardid = c.id
WHERE c.id = 1

答案 1 :(得分:0)

假设每个子查询返回一条记录,则可以通过以下方式使用交叉联接:

insert into concediati (nume, prenume, idclient, idrent, idcar) 
select 
    c1.firstname,
    c1.lastname, 
    c2.id, 
    c3.id,
    c4.id
from 
    clients c1, 
    clients c2, 
    rentcar c3, 
    cars c4
where 
    c1.id = 1 and 
    c2.idteam = 1 and
    c3.idteam = 1 and 
    c4.idteam = 1

或者,使用联接:

insert into concediati (nume, prenume, idclient, idrent, idcar) 
select 
    c1.firstname,
    c1.lastname, 
    c2.id, 
    c3.id,
    c4.id
from 
    (
        (
            clients c1 inner join clients c2 on c1.id = c2.idteam
        )
        inner join rentcar c3 on c1.id = c3.idteam
    )
    inner join cars c4 on c1.id = c4.idteam
where 
    c1.id = 1

(由于未指定RDBMS,因此我假定要使用MS Access语法进行联接,因为在进行包围式处理时比较麻烦)。