0

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?

1
  • Just Click HERE It will help you to Understand the Foreign Key Concept... Commented Jul 11, 2012 at 20:21

1 Answer 1

2

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'
Sign up to request clarification or add additional context in comments.

1 Comment

+1. This is the way to go. But, if we don't have a guarantee of uniqueness of the servers.name column, we can add a LIMIT 1 to avoid the insert adding more than 1 row. Also, there's a possibility that the servername value will not be found, so the app would need to check that rows_affected > 0, and handle the condition when it isn't, rather than assuming a row was successfully inserted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.