Jump to content

how to select post title only when it exists? (need help with if statement)


rain13

Recommended Posts

Hello

 

 

I want to select warn.*, post.PostTitle. The problems is that some rows in warn does not have matching post. In that case I would like to select '' as PostTitle. So I tried a little if statement, but It gives error. Could anyone show me how to correctly write query that selects warn.*, post.PostTitle and that would select constant empty string as PostTitle if there is no post that matches given criteria?

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF (EXISTS(SELECT 1 FROM post WHERE post.UserID=37)) THEN SELECT warn.*, p' at line 1
IF (EXISTS(SELECT 1 FROM post WHERE post.UserID=37)) THEN    SELECT warn.*, post.PostTitle FROM warn,post WHERE warn.UserID=37 AND  post.UserID=warn.UserIDELSE    SELECT warn.*, "" FROM warn WHERE warn.UserID=37END IF

Here are some cases where post does not exist:1) Administrator or moderator have deleted post after issuing warning for it.2) warning was issued for something else than specific post.In these cases I would like to select '' as PostTitle.

Edited by SoItBegins
Link to comment
Share on other sites

Thanks for hint. Meanwhile I managed to do it with UNION ALL. Is would LEFT JOIN be any better?Here's my solution incase anyone happens to find this post via search engine or I happen to loose it.

SELECT warn.*, "" AS PostTitle FROM warn WHERE warn.UserID=37 AND (NOT EXISTS (SELECT 1 FROM post WHERE post.UserID=warn.UserID AND post.ID = warn.PostID))UNION ALLSELECT warn.*, post.PostTitle FROM warn,post WHERE warn.UserID=37 AND  post.UserID=warn.UserID AND post.ID = warn.PostID
Edited by SoItBegins
Link to comment
Share on other sites

It's this query:

 

SELECT warn.*, post.PostTitle FROM warn,post WHERE warn.UserID=37 AND post.UserID=warn.UserID

 

But with a left join instead of an inner join. Separating tables with a comma like that is an inner join, you want to use a left join instead.

Link to comment
Share on other sites

Edit:

 

Got it. I wasn't quite used to left join. Actually I've never used it with only 1 select

 

So thats' what I've got

SELECT warn.*, post.PostTitle FROM warn LEFT JOIN post ON post.ID = warn.PostID AND post.UserID=warn.UserID WHERE warn.UserID=37
Edited by SoItBegins
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...