0

所以我有2张桌子:

  1. 顾客
  2. 文件

我如何进行连接以显示最新记录,即由 created_on DESC

例如

SELECT customers.name, files.last_file_submission

如果我有:

customer A
 - File 1, created_on 10-10-2012
 - File 2, created_on 11-10-2012

我想为每个客户返回一行:

customer A, 11-10-2012
4

2 回答 2

1

每个文件:

SELECT c.name, f.submit_date
FROM files f, customers c
WHERE f.submitter = c.id
ORDER BY f.submit_date DESC

每个用户:

SELECT DISTINCT c.name, MAX(f.submit_date)
FROM files f, customers c
WHERE f.submitter = c.id
ORDER BY MAX(f.submit_date) DESC
GROUP BY c.id
于 2012-10-08T05:28:48.987 回答
0

无论客户是否有任何文件记录,它将带来所有客户及其最新的文件日期。

SELECT DISTINCT customer.id, customer.name, MAX(file.submit_date)
FROM customer LEFT JOIN file ON customer.id = file.submitter
GROUP BY customer.id, customer.name

您可以更改LEFTINNER以限制仅在文件表上有参考的客户之间的连接。

于 2012-10-08T05:45:08.057 回答