Skip to content
Advertisement

How to insert into a row, a value from other table?

I have 3 Mysql tables.

A table with the classes and the labs and their id.

A table with the teachers_list and their subject. A table which is going to be the schedule.**

I want to randomly assign one of the physicists to one of the physics labs on my third table which is going to be the schedule.

INSERT INTO schedule(teacher_name, class_id)
VALUES (select teacher_name from teachers_list where subject="Physicist” order by rand() limit 1, 

select id from lab_list where lab="Physics_lab" order by rand() limit 1);

**This one doesn’t work 🙁

Can you help me?**

Advertisement

Answer

I think that you want the insert ... select syntax, along with a subquery:

insert into schedule(teacher_name, class_id)
select 
    (
        select teacher_name 
        from teachers_list 
        where subject = 'Physicist'
        order by rand()
        limit 1
    ),
    id
from lab_list
where lab = 'Physics_lab'
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement