Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can you insert into a table where a value is a declared variable in mysql?

Is it possible to do something like this ?

INSERT INTO homework(teacherId, class, name, dueDate)
VALUES(teacherId, "12A1", "trig", "tomorrow")
teacherID = (
        SELECT teacherId
        FROM teacherlogins
        WHERE teacherid = 5
    )

I know this query is incorrect, but is it possible to do this another way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are several ways to do it. One is in the comment above from Barbara, using INSERT…SELECT syntax:

INSERT INTO homework(teacherId, class, name, dueDate)
SELECT teacherId, '12A1', 'trig', 'tomorrow'
FROM teacherlogins
WHERE teacherid = 5;

Here’s another using a scalar subquery operand:

INSERT INTO homework(teacherId, class, name, dueDate)
VALUES((SELECT teacherId FROM teacherlogins WHERE teacherid = 5 LIMIT 1),
    '12A1', 'trig', 'tomorrow')

Here’s another using a user-defined variable and SELECT INTO syntax:

SELECT teacherId INTO @t FROM teacherlogins WHERE teacherid = 5;

INSERT INTO homework(teacherId, class, name, dueDate)
VALUES(@t, '12A1', 'trig', 'tomorrow');

Here’s another: 🙂

INSERT INTO homework(teacherId, class, name, dueDate)
VALUES(5, '12A1', 'trig', 'tomorrow');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading