Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get rows matching all items from an array

Tags:

sql

php

mysql

I can do it with a loop or an alternate solution, but this would mean time consuming (on page loading).... So I would like to know if there is a 'one query' solution.

I have a table containing 4 columns:

id   class    day    hour
 1   9b3      1      3      
 2   9b4      1      3
 3   9b5      1      3
 4   9b3      1      5
 5   9b4      2      6
 6   9b5      2      6
 7   9b4      4      7
 8   9b3      3      6
 9   9b4      3      6
 10  9b5      3      6

What I need is to recover the day and hour matching all three classes 9b3, 9b4, 9b5 at the same day and hour.

In the example above, the result should be:

day   hour
1      3
3      6
like image 272
Basil Gass Avatar asked Jul 23 '26 19:07

Basil Gass


2 Answers

Try this:

SELECT day,hour
FROM yourTableName
WHERE class IN ('9b3','9b4','9b5')
GROUP BY day,hour
HAVING COUNT(class) = 3;

sqlfiddle demo

like image 100
Filipe Silva Avatar answered Jul 25 '26 08:07

Filipe Silva


also that works...

SELECT day,hour
FROM Table1
WHERE (class = '9b3' or class =  '9b4' or class = '9b5')
GROUP BY day,hour
HAVING COUNT(class) = 3;
like image 31
tanaydin Avatar answered Jul 25 '26 07:07

tanaydin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!