我是MYSQL初学者,我遇到查询问题:
我有两张桌子(来电,来电失败)。
让我们说来电表是:
+---------------+----------+
| called_number | duration |
+---------------+----------+
| 1010101 | 13 |
| 1010101 | 18 |
| 1010101 | 20 |
| 2020202 | 50 |
| 2020202 | 20 |
| 3030303 | 10 |
| 4040404 | 30 |
+---------------+----------+
来电失败表格为:
+---------------+----------------+
| called_number | release_reason |
+---------------+----------------+
| 1010101 | -1 |
| 1010101 | -1 |
| 2020202 | -1 |
| 3030303 | 406 |
| 4040404 | 503 |
| 5050505 | -1 |
| 5050505 | -1 |
| 6060606 | -1 |
+---------------+----------------+
我想选择被叫号码> 1,当持续时间小于25时,或者它使release_reason = -1。超过1次。
但是如果caller_number的持续时间超过25,即使它有release_reason = -1,也不要选择它。
结果将是:
+---------------+-------+
| called_number | count |
+---------------+-------+
| 1010101 | 3 |
| 5050505 | 2 |
+---------------+-------+
我的代码是:
( 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
)
答案 0 :(得分:2)
您可能正在寻找加入
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
但是对于工会来说,你可能需要持续时间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
答案 1 :(得分:1)
问题上的差距很小。
这是我对你想要实现的目标的最佳猜测
SELECT T1.called_number,(T1.C1 + T2.C2)AS count FROM(SELECT called_number,COUNT()AS C1 FROM调用WHERE持续时间&lt; 25 GROUP BY called_number)T1 JOIN(SELECT called_number,COUNT()AS C2 FROM callsfailed WHERE release_reason = -1 GROUP BY called_number)T2 ON T1.called_number = T2.called_number WHERE(T1.C1 + T2.C2)&gt; 1;
答案 2 :(得分:1)
您可以将UNION用作派生表,并像这样选择
positive_threshold_0.500000_mean
你有结果