加入但只能获得一次最新日期

时间:2011-10-19 19:47:38

标签: mysql

我有这样的数据。
customer

| customerId | fullName     | sex
| 1          | Budi Arsana  | Male
| 2          | Peter Parker | Male

和其他表名transaction

| Id | bookingDate | customer
| 1  | 2011-09-01  | 1
| 2  | 2011-09-30  | 1
| 3  | 2011-09-01  | 2

我希望获得结果,结合了2个表,选择拥有交易的客户,然后只获得最新日期的1个交易。喜欢这个

| customerId | fullName     | sex  | transId | bookingDate
| 1          | Budi Arsana  | Male | 2       | 2011-09-30
| 2          | Peter Parker | Male | 3       | 2011-09-01

2 个答案:

答案 0 :(得分:5)

SELECT c.customerId, c.fullName, c.sex, t.Id AS transId, t.bookingDate
    FROM customer c
        INNER JOIN (SELECT customer, MAX(bookingDate) AS MaxDate
                        FROM transaction
                        GROUP BY customer) q
            ON c.customerId = q.customer
        INNER JOIN transaction t
            ON q.customer = t.customer
                 AND q.MaxDate = t.bookingDate;

答案 1 :(得分:2)

使用自我排除加入:

SELECT c.customerId, c.fullName, c.sex, t.Id AS transId, t.bookingDate
  FROM customer c
       LEFT JOIN transaction t ON t.customer = c.customerId
       LEFT JOIN transaction t2 ON t2.customer = t.customer
   AND t2.bookingDate > t.bookingDate 
 WHERE t2.Id IS NULL;

原则是您创建另一个连接到transaction表(t2)的工作副本,并使用它来从最终结果集中除去{{1}中的最新记录}(transaction)。

警告:如果您每位客户每天有多次预订,这将无效。在这种情况下,您可能希望从日期更改为时间戳。