在MySql中,如何将数据插入引用其他三个表的表中,然后选择该数据?

时间:2014-09-20 18:13:44

标签: mysql select join insert multiple-tables

我有一个appointment表引用了其他三个表:counselorclientroom。我需要将这三个表中的数据插入到appointment表中。我按如下方式创建了appointment表:

create table appointment(
    AppointmentID int default next value for NDFCID primary key,
    CounselorID int not null references counselor,
    ClientID int not null references client,
    RoomNumber int not null references room,
    AppointmentDate date,
    StartTime time(0),
    Duration varchar(50)
);

在我将数据插入其他三个表后,我想将数据插入到约会中,这是我到目前为止所做的:

insert into appointment(counselor.firstName, client.firstName, room.RoomName, AppointmentDate,StartTime,Duration)
  values
  ('Audrey', 'Sarah', 'Clear sky', '10/1/2014', '8:00:00', '90');

有没有办法做到这一点,我不必将字符串名称硬编码到插入中,只是从表中引用它们?我想在appointment中插入许多值。我插入后,如何选择要显示的数据?我应该在插入声明中选择并加入所有内容,还是会在之后发生?

1 个答案:

答案 0 :(得分:0)

使用SELECT语句从其他表中获取具有特定名称的ID。

INSERT INTO appointment (CounselorID, ClientID, RoomNumber, AppointmentDate, StartTime, Duration)
SELECT c.id, cl.id, r.roomNumber, "10/1/2014", "8:00:00", "90"
FROM counselor AS c
CROSS JOIN client AS cl
CROSS JOIN room AS r
WHERE c.firstName = "Audrey"
AND cl.firstName = "Sarah"
AND r.roomName = "Clear sky"