Jump to content

Archived

This topic is now archived and is closed to further replies.

Buyocat

Using an If clause in MySQL

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.

Share this post


Link to post
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..

Share this post


Link to post
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

Share this post


Link to post
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.

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

×

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.