Jump to content

Help Creating a Query


computermax2328

Recommended Posts

Hi All,

 

I have been trying to figure out this query for a couple of days now. I have been coming back to it over and over again and I still can't wrap my head around it. Care to give some help or ideas?

 

I did not design this database so I am not stumping myself. I have a table of posts which have an ID associated with them. When I associate an image with this post the URL of that image gets put into a separate table along with the post's ID. The image URL has it's own ID as well, which is different than the post's. So it looks like this.

 

Table 1: Post id

 

Table 2: Post id, image URL id, image URL

 

These images are going to be in a loop of posts so I can't pull the id as a variable into the query. It is almost like I need to say SELECT * FROM table WHERE id="This specific post's id";

 

Does that make sense?

 

Thanks in advance,

Link to comment
Share on other sites

So I was gonna do something like "SELECT title, content, id FROM posts," then loop it through, and assign variables to the values that come out. Then run a query through like "SELECT * FROM other_table WHERE id=$id."

 

Does that make sense. I know that isnt right. I just don't know know to unique variable into the first query. 

Link to comment
Share on other sites

JOIN

 

Select all the data you need from both tables in a single query:

 

 

SELECT title, content, p.id, imageUrl
FROM posts AS p LEFT JOIN postImages as i ON p.id = i.postid
-- YADA YADA YADA
The LEFT JOIN will ensure you get POSTS even if they do not have an associated image. Leave LEFT out of the JOIN if you only want posts that have images.

 

The problem with this approach is that any POST that has more than one image associated with it, will be in the resultset multiple times (once for each image).

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.