I have a MySQL table
Cat | User | Active |
---|---|---|
12 | 45 | 0 |
12 | 54 | 0 |
13 | 76 | 0 |
12 | 33 | 1 |
15 | 66 | 0 |
12 | 12 | 0 |
12 | 22 | 0 |
I run a query to select based on category id(cat).
fore ex. If I am querying for cat 12 then the rows with active 1 should be the result even if there are rows with active=0.
Cat | User | Active |
---|---|---|
12 | 33 | 1 |
If active= 1 is not present and if there are active = 0 then the rows with active=0 should be the result.
Cat | User | Active |
---|---|---|
12 | 45 | 0 |
12 | 54 | 0 |
12 | 12 | 0 |
12 | 22 | 0 |
Hope it should be possible to do all these in one single query with IF.
But, I could not figure out. Need help.
Thanks
2
Answers
What you could do is on your
WHERE
clause check theCOUNT()
ofActive
rows and depending on the number perform the appropriate equality. For example:https://dbfiddle.uk/4K8DHHmw
fiddle