Search code examples
sqlselectinsertinner-join

is it possible to make an insert into with a select inner join where a parameter of the insert is inserted as a value?


I'm trying to make a query that seems borderline to me. Briefly I have 4 tables, I want to make an insert in one of those, take a portion of data from the other 3 and a data of the insert I want to take it dynamically and then as a value ("data time"). This is what I have done so far, but it gives me an error in the last line

INSERT INTO prenotazioni(`idMateria`,`idDocente`,`idUtente`,`data`)
SELECT corsi.id, docenti.id, utenti.id
FROM (((prenotazioni
INNER JOIN corsi ON prenotazioni.idMateria = corsi.id)
INNER JOIN docenti ON prenotazioni.idDocente = docenti.id)
INNER JOIN utenti ON prenotazioni.idUtente = utenti.id)
WHERE corsi.materia = 'italiano' && docenti.nome = 'Mimmo' && utenti.id = 4
VALUES ('2022-24-5 16:00:00')

Solution

  • Just add the datetime literal to the end of the select list:

    INSERT INTO prenotazioni (idMateria, idDocente, idUtente, data)
    SELECT c.id, d.id, u.id, '2022-24-5 16:00:00'
    FROM prenotazioni p
    INNER JOIN corsi c ON p.idMateria = c.id
    INNER JOIN docenti d ON p.idDocente = d.id
    INNER JOIN utenti u ON p.idUtente = u.id
    WHERE c.materia = 'italiano' && d.nome = 'Mimmo' && u.id = 4;
    

    Note that I have also introduced table aliases (i.e. nicknames for the tables) for improved readability.