James Dawson
James Dawson

Reputation: 5409

MySQL JOIN when inserting data

I have two tables: images and servers. Here's the schema relating to those two tables:

id, name, uploaded, views, server_id

id, name, description, drive_space, enabled

On the images table, server_id is a foreign key to the id field in the servers table. Pretty simple stuff. Many images belong to one server.

When I insert an image, it has to have a key pointing to the server the image is hosted on. When I insert the row, I'm given the name of the server (not its id) so I can't just insert it. I can achieve what I want with two queries (one to get the server ID and another to insert the image into the database) but idealy I want it done in one query with a JOIN as it's best practice.

I'm almost clueless with JOINS when it comes to SELECT statements and even more so with an INSERT. Can anyone help me out?

Upvotes: 0

Views: 141

Answers (1)

Mark Byers
Mark Byers

Reputation: 838116

No need for a join. Just use a INSERT ... SELECT ...:

INSERT INTO images
(name, uploaded, views, server_id)
SELECT 'imagename', CURTIME(), 0, id
FROM servers
WHERE name = 'servername'

Upvotes: 2

Related Questions