How can I INSERT new values and values from an already existing table?

Viewed 135

I'm currently learning MySQL and have learned the INSERTO INTO statement and the INSERT INTO SELECT statement.

The INSERT INTO statement works like this:

INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);

While the INSERT INTO SELECT works like this:

INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;

What I'm trying to do is add new values while also adding values that I already have stored in another table.

con.query("INSERT INTO vehicles (vehicleType, vehicleModel, vehicleOwner, vehicleSpawnX, vehicleSpawnY, vehicleSpawnZ)")

From the query above, I already have the vehicleOwner value stored in another table, while the other ones I've just gotten. How can I do this? Add a VALUES statement before SELECT? I'm using SQL Workbench 8.0 and JavaScript. Also, all the values are NOT NULL, so I can't make two different queries, unless on the first one I add temporary values that I'll update on the second one.

What I want to replace:

  • vehicleType -> "players"
  • vehicleModel -> vehicleCreate.model
  • vehicleOwner -> playerID FROM players table
  • vehicleSpawnX -> pos.x
  • vehicleSpawnY -> pos.y
  • vehicleSpawnZ -> pos.z

Thanks!

2 Answers

It's not possible... But you can select data and store that on variables, then you will store it in another table

You would construct a query. Your data model is a bit hard to follow since you give no examples of the data or of what you really want to do.

So let me give a simpler example. Say, you have a table with two columns for two players and you want to put the ids into a table -- but using their names. The query would look like:

insert into pairs (playerId1, playerId2)
    select p1.playerId, p2.playerId
    from players p1 join
         players p2
         on p1.name = ? and p2.name = ?;

The ? are for parameter placeholders. I assume you know to aways use parameters when passing values into a query.

Related