簡體   English   中英

MySQL:如何從一個表中查找日期晚於其他表的日期的記錄計數

[英]MySQL: How to find a count of records from one table where date is later than date from other table

有 2 個 MariaDB 表:

表格1

|------+----------------------+
| phone | calldate            |
|-------+---------------------+
| 123   | 2020-01-01 17:01:00 |
| 456   | 2020-01-01 17:01:00 |
| 789   | 2020-01-01 17:01:00 |
|------+---------------------+|

表2

|------+---------------------+
| phone| calldate            |
|------+---------------------+
| 123  | 2020-01-01 16:00:00 |
| 123  | 2020-01-01 17:00:00 |
| 456  | 2020-01-01 17:00:00 |
| 123  | 2020-01-01 18:00:00 |
| 456  | 2020-01-01 18:00:00 |
| 789  | 2020-01-01 18:00:00 |
|------+---------------------+

預期結果:

|-------+------+
| phone | count|
|-------+------+
| 123   | 2    |
| 456   | 1    |
|-------+------+

如何通過電話從 table2 中查找 calldate 早於 table1 組中 calldate 的記錄計數?

如何通過電話從 table2 中查找 calldate 晚於 table1 組的 calldate 的記錄計數?

這聽起來像一個join和聚合:

select t2.phone, count(*)
from table2 t2 join
     table1 t1
     on t2.phone = t1.phone and t2.calldate > t1.calldate
group by t2.phone;

隨着EXISTS

select t2.phone, count(*) count
from table2 t2 
where exists (
  select 1 from table1 t1
  where t1.phone = t2.phone and t1.calldate > t2.calldate
)  
group by t2.phone

請參閱演示
結果:

| phone | count    |
| ----- | -------- |
| 123   | 2        |
| 456   | 1        |

如果不起作用,您也可以嘗試使用 where 子句:

select count(table2.phone) from table2 t2 
full outer join table1 t1 on t2.phone=t1.phone
where t2.calldate >t1.calldate
group by t2.phone

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM