【问题标题】:MySQL: How to find a count of records from one table where date is later than date from other tableMySQL:如何从一个表中查找日期晚于另一表中的日期的记录计数
【发布时间】:2020-08-19 04:54:27
【问题描述】:

有 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 的记录计数?

【问题讨论】:

  • 这两个号码的电话似乎都晚了。
  • 是的,我弄错了。我编辑了问题
  • table1 每个phone 是否只有一行?如果没有,解决方案会变得更加混乱。

标签: mysql sql mariadb


【解决方案1】:

如何通过电话从 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;

【讨论】:

    【解决方案2】:

    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
    

    请参阅demo
    结果:

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

    【讨论】:

      【解决方案3】:

      如果不起作用,您也可以尝试使用 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
      

      【讨论】:

        猜你喜欢
        • 2016-03-15
        • 2015-03-07
        • 1970-01-01
        • 2018-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-09
        • 2021-01-11
        相关资源
        最近更新 更多