I'm a MYSQL Beginner and I have a Problem With A Query :
I have two tables ( calls , callsfailed ).
Lets Say calls Table is :
+---------------+----------+
| called_number | duration |
+---------------+----------+
| 1010101 | 13 |
| 1010101 | 18 |
| 1010101 | 20 |
| 2020202 | 50 |
| 2020202 | 20 |
| 3030303 | 10 |
| 4040404 | 30 |
+---------------+----------+
And callsfailed Table is :
+---------------+----------------+
| called_number | release_reason |
+---------------+----------------+
| 1010101 | -1 |
| 1010101 | -1 |
| 2020202 | -1 |
| 3030303 | 406 |
| 4040404 | 503 |
| 5050505 | -1 |
| 5050505 | -1 |
| 6060606 | -1 |
+---------------+----------------+
I want to select the called_number > 1, when it makes duration less than 25, OR it makes release_reason = -1. more than 1 time.
BUT If the caller_number made a duration more than 25, don't select it even when it has a release_reason = -1.
So the result will be :
+---------------+-------+
| called_number | count |
+---------------+-------+
| 1010101 | 3 |
| 5050505 | 2 |
+---------------+-------+
MY CODE IS :
( SELECT called_number, duration, COUNT(*) count
FROM calls
GROUP BY called_number
Having COUNT(called_number) > 1 and duration < 25
)
UNION
( SELECT called_number, release_reason, COUNT(*) count
FROM callsfailed
GROUP BY called_number
Having COUNT(called_number) > 1 and release_reason = -1
)
Could be you are looking for a join
select t1.called_number, t1.duration, t1.count
from
( SELECT called_number, duration, COUNT(*) count
FROM calls
GROUP BY called_number
Having COUNT(called_number) > 1 and duration < 25
) t1
left join
( SELECT called_number, release_reason, COUNT(*) count
FROM callsfailed
GROUP BY called_number
Having COUNT(called_number) > 1 and release_reason = -1
) t2 on t1.called_number = t2.called_number
But for the union could be you need where for duration e release_reason
SELECT called_number, duration, COUNT(*) count
FROM calls
WHERE duration < 25
GROUP BY called_number
Having COUNT(called_number) > 1
union
SELECT called_number, release_reason, COUNT(*) count
FROM callsfailed
GROUP BY called_number
where release_reason = -1
Having COUNT(called_number) > 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With