我想使用MySql中的join将多个记录中的最新行获取到表中
我已经在堆栈溢出和其他博客中引用了一些帖子,并试图解决我的问题,但我认为我的情况还有其他问题。
我有2个表:第1个是优惠券,第2个是coupon_data
表中的优惠券带有所有优惠券代码,并且coupon_data包含优惠券的详细信息及其兑换日期和其他信息 在这种情况下,优惠券将被扫描多次,因此它具有多个扫描日期
喜欢
优惠券
ClassA {
int functionA() {
...condition(started_execution);
int a=0;
a++;
printf(....a);
return a;
}
};
void startExecution(void *arg) {
/*casting code object A*/
A->functionA();
}
int main() {
ClassA *A = new ClassA();
pthread_create(....,startExecution,(void *)A);
....wait_for(started_execution);
delete A;//just want to know the behaviour and not join method.
}
coupon_data
+----------+--------------+
| coupon_id | coupon_code |
+----------+--------------+
| 1 | coupon1 |
| 2 | coupon2 |
| 3 | coupon3 |
+----------+--------------+
现在我需要最新的场景优惠券及其scan_date
我试图通过此查询获取数据
+----+------------+-------------+
| id | scan_date | coupon_code |
+----+------------+-------------+
| 1 | 2018-04-18 | coupon1 |
| 2 | 2018-04-20 | coupon2 |
| 3 | 2018-04-22 | coupon2 |
| 4 | 2018-04-25 | coupon1 |
| 5 | 2018-04-27 | coupon1 |
| 6 | 2018-04-28 | coupon3 |
+----+------------+-------------+
但是没有运气。 我的目标是获取这样的数据。
SELECT *
FROM coupon c
left JOIN (
SELECT MAX(id) max_id, scan_date,coupon_code
FROM coupon_data
GROUP BY coupon_code
) c_max ON (c_max.coupon_code = c.coupon_code)
left JOIN coupon_data cd ON (cd.coupon_code = c_max.coupon_code)
任何回复都是值得的。
答案 0 :(得分:0)
如果您确实只需要这么多的数据,并且您的表中包含您所提到的相同数据,那么您就不需要子查询和联接。
尝试类似
SELECT c.coupon_code, cd.dt FROM coupon c INNER JOIN (
SELECT MAX(scan_date) AS dt , coupon_code AS cod FROM
coupon_data GROUP BY coupon_code
) cd
ON cd.cod = c.coupon_code
这将为您返回预期的结果。
尝试这个Demo