1

I have a MySQL relational database which stores customers in one table, and then another table which stores various contacts/conversations/engagements with them. See the examplar schema below:

Customers
customerId
forename
surname

Contacts
contactId
customerId
correspondenceDescription
contactDate

I need to be able to query the database and be able to access the date (contactDate) of the most recent time we have been in touch with them. I've seen a few other questions on here, but I dont seem to be able to find one which suits my needs.

Can anyone help? Many thanks.

4

3 回答 3

1

试试这些查询:

检索所有客户的最新联系日期(当您将所有客户显示为列表时):

SELECT Customers.*, max(Contacts.contactDate) as Most_Recent
from Customers left join Contacts
ON Customers.customerId = Contacts.customerId
GROUP BY Customers.customerId
ORDER BY Most_Recent desc

要检索客户最近的联系日期(将 id 1 更改为客户的 id):

SELECT Customers.*, Contacts.contactDate as Most_Recent
from Customers left join Contacts
ON Customers.customerId = Contacts.customerId
where Customers.customerId = 1
ORDER BY Most_Recent desc
于 2013-09-08T22:23:20.703 回答
1

当然,这是一个起点。您需要按客户 ID 对联系人进行分组,因此我将从以下内容开始:

SELECT
    MAX(contactDate), customerId
FROM
    Contacts
GROUP BY
    customerId

从那里,您可以LEFT JOIN到您的客户表,您将能够看到每个客户的最后联系日期。如果您确定每个客户至少有一个联系人,您可以将其交换为INNER JOIN,这应该会加快速度。

于 2013-09-08T22:17:43.707 回答
0

我通常会鼓励人们明确地命名列,而不是使用明确的连接语法——某些版本的 MySQL 会做一些愚蠢的事情。聚合通常比执行有限制的订单要慢,所以我会这样做:

    select customerId, forename, surname, contactId, correspondenceDescription, contactDate
        from customer, contacts
        where customer.customerId = contacts.customerId
        and customer.customerId = ?
        order by contactDate desc
        limit 0,1
于 2013-09-08T22:36:10.777 回答