所以我有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
每个文件:
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
无论客户是否有任何文件记录,它将带来所有客户及其最新的文件日期。
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
您可以更改LEFT
为INNER
以限制仅在文件表上有参考的客户之间的连接。