Jump to content

Using an If clause in MySQL


Buyocat

Recommended Posts

Can anyone tell me how to construct the following statment so it works?  Currently I get an error - at or around the "and" portion of it.

[code]
SELECT SUM(IF(s.started >= 1140211367 AND s.ended <= 1151779520)) as num_logs
FROM fp_session_history s
[/code]

I have tried using && as well with no luck.
Link to comment
Share on other sites

look at http://dev.mysql.com/doc/refman/5.1/en/partitioning-range.html

SELECT SUM(IF(s.started >= 1140211367 AND s.ended <= 1151779520)) as num_logs
FROM fp_session_history

you would not use as num_logs either as that wouldn't hold a value..
Link to comment
Share on other sites

OK - guessing game - are you trying to count the rows where (s.started >= 1140211367 AND s.ended <= 1151779520) ?

if so,

SELECT COUNT(*) WHERE s.started >= 1140211367 AND s.ended <= 1151779520


Are you trying to get the total of another column depending on the IF condition.

If so the IF syntax is IF(condition, value if true, value if false)

SELECT SUM(IF(s.started >= 1140211367 AND s.ended <= 1151779520), anothercol, 0 ) as num_logs
FROM fp_session_history s
Link to comment
Share on other sites

Thanks for the hand fellas, Barand I ended up using what you suggested, although I discovered that this works and gets the same result...
[code]
SELECT SUM(IF(time1 >= timeA && time2 <= timeB), 1, 0) ...
[/code]
(don't ask me what me the 1 and 0 do, I think that it adds one if the if is true and zero otherwise)  At any  rate that fetches the same result as
[code]
SELECT COUNT(*) ... WHERE time1 > sometime AND time2 < someothertime
[/code]
I went with count, it just seems more readable.
Link to comment
Share on other sites

I'd go with the COUNT(*) WHERE option.

The times I'd use IF is when a client wants a weekly report like

[pre]Product          Monday  Tuesday  ....  Friday      Weekly_Total[/pre]

Then my query would be something like

SELECT product, SUM(IF weekday=1, sales, 0) as monday, SUM(IF weekday=2, sales, 0) as tuesday... etc
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.