Can anyone help me with this query

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
irr1449
Forum Newbie
Posts: 1
Joined: Sun Jul 15, 2007 4:19 pm

Can anyone help me with this query

Post by irr1449 »

This is kind of complex (for me) and I was wondering if anyone could help.

I have 3 Tables.

User, which has a primary key, user_id
Story, which has an primary key, story_id
SavedStory, which contains only 2 fields, user_id and story_id. When the user saves a story it just writes the user_id and the story_id that they wish to save.

I want to do a single select to load stories, but I also want to see if the user has saved the story.

Is there anyway I can do like a conditional select, where I can select stories.* and SavedStory.UserId and have the UserId be null if its not saved, and have user_id be populated if it is saved?

So the resultset might look like this if the user has saved the story.

Story.story_id, Story.(other fields), SavedStory.user_id (this would have the user_id field populated so I know its saved)

A resulset with it not saved would just have user_id = null, but would still return all the stories.

Does that make sense? I know I could easily do this with multiple selects, but it would be extremely slow.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Sounds like a LEFT/RIGHT JOIN.
Post Reply