MySQL Insert results of select

时间:2016-10-20 12:39:39

标签: mysql

I have a many to many relationship and am trying to insert a new relationship. At the point I'm doing the insert I don't know the id so would need to look it up. My table structure looks something like this:

**person**
id
name

**film**
id
title

**person_film**
personId
filmId

Given a person's id and a list of film titles (but not their ids) I'm only able to insert these relationships into the person_film table in two steps.

SELECT id FROM film WHERE title="film1" OR title="film2";

Then the results of that can be used in an insert:

INSERT INTO person_film (personId, filmId) VALUES (5, 5),(5, 7);

Is there a way of doing this in a single SQL statement?

2 个答案:

答案 0 :(得分:2)

You can do it with a subquery:

INSERT INTO person_film (personId, filmId)
  SELECT 5, id FROM film
    WHERE title IN("film1","film2");

Here the 5 is the personId value and the filmId will be retrieved from the film table.

答案 1 :(得分:0)

Use numeric literals with aliases inside a SELECT statement. No () are necessary around the SELECT component.

INSERT INTO person_film (personId, filmId)
  SELECT
    /* Literal number values with column aliases */
    1 AS fpersonId,
    2 AS filmId,

  FROM film 
  WHERE title="film1" OR title="film2";

Note that in context of an INSERT INTO...SELECT, the aliases are not actually necessary and you can just SELECT 1, 2 but in a normal SELECT you'll need the aliases to access the columns returned.