根据唯一键之间的比较选择另一列的最新值

时间:2018-07-20 09:03:45

标签: mysql

我要实现的目标是基于同一msisdn获取另一列的最新日期(如果存在多个链接到其他msisdn的{​​{1}} s)。 (您可以假设imsi更多地是唯一列)

出于演示目的简化表

我有两个如下表:

操作员

imsi

客户

+--------+--------+---------------------+
|  imsi  | msisdn |    last_accessed    |
+--------+--------+---------------------+
| 74583  | 004442 | 2018-04-05 16:20:32 |
+--------+--------+---------------------+
| 94210  | 023945 | 2017-02-13 11:27:14 |
+--------+--------+---------------------+
| 59123  | 004442 | 2018-07-15 05:24:55 |
+--------+--------+---------------------+
| 61234  | 089923 | 2018-07-21 16:13:29 |
+--------+--------+---------------------+

以下结果是我的目标。如果我搜索+--------+--------------+---------------------+ | imsi | company_id | business_plan | +--------+--------------+---------------------+ | 74583 | FEX | yearly | +--------+--------------+---------------------+ | 94210 | AOH | trial | +--------+--------------+---------------------+ | 59123 | BIOI | monthly | +--------+--------------+---------------------+ | 61234 | OOX | simple | +--------+--------------+---------------------+ ,它将返回74583

2018-07-15 05:24:55

以下查询几乎返回了我尝试实现的结果,但没有根据上表返回最新日期。

+--------+--------------+---------------------+----------------------+
|  imsi  |  company_id  |    business_plan    |  last_accessed_date  |
+--------+--------------+---------------------+----------------------+
| 74583  |      FEX     |       yearly        |  2018-07-15 05:24:55 |
+--------+--------------+---------------------+----------------------+

3 个答案:

答案 0 :(得分:2)

我们可以尝试使用select子句中的相关子查询来做到这一点:

SELECT
    c.imsi,
    c.company_id,
    c.business_plan,
    (SELECT MAX(t.last_accessed) FROM operator t
     WHERE t.msisdn = o.msisdn) last_accessed_date
FROM customer c
INNER JOIN operator o
    ON c.imsi = o.imsi
WHERE c.imsi = '74583';

按照下面的链接获取SQLFiddle演示。

Demo

答案 1 :(得分:1)

此查询将为每个imsi返回last_accessed_date:

select
  o1.imsi,
  o1.msisdn,
  max(o2.last_accessed) as last_accessed_date
from
  operator o1 inner join operator o2
  on o1.msisdn = o2.msisdn
group by
  o1.imsi,
  o1.msisdn

(我将自己与Operators表结合在一起,以基于msisdn列获取上次访问的日期)。然后,您可以将此查询与客户表一起加入:

select
  c.imsi,
  c.company_id,
  c.business_plan,
  coalesce(l.last_accessed_date, 'Never') as last_accessed_date
from
  customer c left join (
    select
      o1.imsi,
      o1.msisdn,
      max(o2.last_accessed) as last_accessed_date
    from
      operator o1 inner join operator o2
      on o1.msisdn = o2.msisdn
    group by
      o1.imsi,
      o1.msisdn
  ) l on c.imsi = l.imsi

然后可以用一些不同的方式来编写它,但是我认为这更容易理解。

请在这里http://sqlfiddle.com/#!9/0f080c/1

答案 2 :(得分:0)

尝试

 SELECT 
      cust.imsi,
      cust.company_id,
      cust.business_plan, 
      ( 
      SELECT MAX(last_accessed) FROM operator AS a WHERE a.msisdn = op.msisdn 
      ) AS last_accessed_date 
FROM customer cust 
      INNER JOIN operator op 
      ON cust.imsi = op.imsi 
WHERE cust.imsi = '74583'