Jump to content

IF statement in SELECT QUERY


Canman2005

Recommended Posts

Hi all

 

I wonder if someone can help.

 

Is it possible to add an "if" statement into a QUERY?

 

For example, I have

 

SELECT p.id, p.name, p.topic FROM people p WHERE p.type = 'Math';

 

But I want to add

 

if(p.topic == 'today') { p.date }

 

to the end of

 

SELECT p.id, p.name, p.topic

 

so it would look something like

 

SELECT p.id, p.name, p.topic, if(p.topic == 'today') { p.date } FROM people p WHERE p.type = 'Math';

 

 

So in real terms it would end up looking like either

 

SELECT p.id, p.name, p.topic FROM people p WHERE p.type = 'Math';

 

or if

 

topic equaled "today"

 

then it would use

 

SELECT p.id, p.name, p.topic,p.date FROM people p WHERE p.type = 'Math';

 

I know the above is not possible, but what would I change it to if at all possible.

 

Thanks all

 

Ed

Link to comment
Share on other sites

thanks, that seemed to work great

 

Just another question, but is it also possible to add something like that at the end of the QUERY, so adding

 

JOIN t.things ON t.userid = p.id

 

to the end of

 

SELECT p.id, p.name, p.topic FROM people p WHERE p.type = 'Math';

 

so I guess it would be something like

 

SELECT p.id, p.name, p.topic FROM people p (p.topic = 'yesterday', JOIN t.things ON t.userid = p.id) WHERE p.type = 'Math';

 

Thanks very much

Link to comment
Share on other sites

Nope. You can however do:

 

SELECT p.id, p.name, p.topic, t.things
FROM people p 
LEFT JOIN 
otherTable AS t ON (t.userid = p.id AND p.topic = 'yesterday')
WHERE p.type = 'Math';

 

which would essentialy have same result.

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.