SQL:明智的城市,明智的产品最新订单ID

时间:2018-11-30 12:19:57

标签: sql phpmyadmin

我有几张桌子: tbl-city

id   city
---------
1     A
2     B
3     C

tbl订单

ord_id   product_id   city   date
----------------------------------
1          1             1   12/3/18
2          1             2   13/3/18
3          2             3   12/4/18
4          1             3   14/4/18
5          3             2   11/2/18
6          1             1   15/1/18
7          2             3   15/4/28

我需要从表orders中获取所有最新订单ID 通过明智的城市和明智的产品 ,使用日期

赞:

ord_id   product_id   city
---------------------------
  1           1          1
  2           1          2
  7           2          3
  5           3          2

我怎么能得到这个?

JOIN / INNER JOIN还是其他方式?

2 个答案:

答案 0 :(得分:0)

您可以使用 correlated 子查询:

select o.*
from orders o
where date = (select max(o1.date)
              from orders o1
              where o1.product_id = o.product_id and o1.city = o.city
             );

答案 1 :(得分:0)

如果ord_id与日期一起增加(通常是这样),则可以进行简单的汇总。

select product_id, city, max(ord_id)
from tbl_ord
group by product_id, city;

否则,典型方法将使用row_number()

select o.*
from (select o.*,
             row_number() over (partition by product_id, city order by date desc) as seqnum
      from tbl_ord o
     ) o
where seqnum = 1;

在旧版本的MySQL中,相关子查询是一个不错的选择。但是,如果您希望每个产品和城市仅排一行,请使用ord_id

select o.*
from tbl_ord o
where o.ord_id = (select o2.ord_id
                  from tbl_ord o2
                  where o2.product_id = o.product_id and o2.city = o.city
                  order by o2.date desc
                  limit 1
                 );
相关问题