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
https://forums.phpfreaks.com/topic/13328-using-an-if-clause-in-mysql/
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
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.
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

Archived

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

×
×
  • 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.