1

I have two MySQL statements (see below), I would like to combine them together so if they both result in a 1 then the end result will be 1. I'm not sure how to construct this and was hoping for some help.

select count(*)
from monitor
where name='job_starttime' and value < ( UNIX_TIMESTAMP( ) -600)
select count(*)
from monitor
where name='job_active' and value = 0

So for example I would like when both statements are true to result in a value of 1, if 1 or none are true it results in a 0.

I nearly achieved it with the below SQL (except it's giving a result for each entry in the table) :(

select
case
when (select count(*) from monitor
where exists (select * from monitor where name = 'job1_active' AND value = 1)
and exists (select * from monitor where name = 'job2_active' AND value = 1)) > 1
then 1
else 0
end
from monitor
asked Nov 4, 2016 at 3:53

1 Answer 1

0

(I am assuming you want the result in a WHERE or some other place for testing?)

This is faster, but is equivalent to COUNT(*)>= 1.

SELECT ...
 WHERE EXISTS ( SELECT * FROM monitor
 WHERE name = 'job_starttime' AND value < ... )
 AND EXISTS ( SELECT * FROM monitor
 WHERE name = 'job_active' AND value = 0 )

Otherwise:

SELECT ...
 WHERE ( SELECT COUNT(*) ... ) = 1
 AND ( SELECT COUNT(*) ... ) = 1

Another tip: false == 0; true == 1.

answered Nov 4, 2016 at 4:14
9
  • @ Rick James - Sorry I'm just not getting it where you mention 'Select ...' what should I replace that with? Commented Nov 4, 2016 at 4:48
  • How about SELECT 1 - you will get either 1 or NULL. Commented Nov 4, 2016 at 5:10
  • So - SELECT 1 WHERE ( SELECT COUNT() ... ) = 1 AND ( SELECT COUNT() ... ) = 1 Commented Nov 4, 2016 at 5:13
  • See if it works for you. Commented Nov 4, 2016 at 5:16
  • Unfortunately not :(, I didn't think it would be this hard to combine these select statements but it is proving difficult. Commented Nov 4, 2016 at 5:17

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.