Take the 2-minute tour ×

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?

share|improve this question
Just Click HERE It will help you to Understand the Foreign Key Concept... –  Rush Jul 11 '12 at 20:21

1 Answer 1

up vote 2 down vote accepted

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

(name, uploaded, views, server_id)
SELECT 'imagename', CURTIME(), 0, id
FROM servers
WHERE name = 'servername'
share|improve this answer
+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. –  spencer7593 Jul 11 '12 at 20:31

Your Answer


