简体   繁体   English

MySQL:如何从一个表中查找日期晚于其他表的日期的记录计数

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

There are 2 MariaDB tables:有 2 个 MariaDB 表:

table1表格1

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

table2表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 |
|------+---------------------+

Expected result:预期结果:

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

How to find a count of records from table2 where calldate is early than calldate from table1 group by phone?如何通过电话从 table2 中查找 calldate 早于 table1 组中 calldate 的记录计数?

How to find a count of records from table2 where calldate is later than calldate from table1 group by phone?如何通过电话从 table2 中查找 calldate 晚于 table1 组的 calldate 的记录计数?

This sounds like a join and aggregation:这听起来像一个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;

With EXISTS :随着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

See the demo .请参阅演示
Results:结果:

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

You can also try with a where clause if that is not working:如果不起作用,您也可以尝试使用 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