MySQL“回溯”获得最近“序列”中的第一条记录

时间:2017-04-02 22:55:24

标签: php mysql

我有2个表:customerscustomers_history

每个表格中的列:

customers.idcustomers.email

customers_history.datecustomers_history.user_idcustomers_history.renewal_error

我有一系列目前处于renewal_error州的客户ID:$failing_customers_ids = array(10, 20);

客户customers_history中的记录示例:

Date user_id renewal_error 28-03-17 10 Insufficient Funds 29-03-17 10 Insufficient Funds 30-03-17 10 NULL 31-03-17 10 Insufficient Funds 01-04-17 10 Insufficient Funds 31-03-17 20 Insufficient Funds 01-04-17 20 Insufficient Funds

我需要查询客户的详细信息,例如电子邮件,以及当前失败序列中的第一次续订错误的日期,因此在这种情况下,查询将导致:

email: someEmailUserID10@example.comdate: 31-03-17

email: someEmaiUserID20l@example.comdate: 31-03-17

我尝试加入表格,然后通过PHP进行处理以“回溯”并得到我想要的内容,但我期待看看我是否可以通过MySQL实现这一切。

1 个答案:

答案 0 :(得分:0)

查询可以是:

$sql = "SELECT DISTINCT * from customers 
 join customers_history 
 on customers.id = customers_history.user_id
 where customers.id IN (:ids) 
 and customers_history.renewal_error = :error
 ORDER BY customers_history.date ASC"