为列的每个不同值MySQL选择一行

时间:2010-06-15 14:02:13

标签: mysql

我有点卡住了,无法理解这个MySQL。以下是我想查询的简略表:

  

print(printID,eventID,printTime)

     

销售(saleID,eventID,saleTime)

我希望获得每个活动的最后打印时间,然后选择具有该eventID且销售时间大于上次打印时间的销售ID。

我尝试了许多方法,但我无法理解。请帮忙!

3 个答案:

答案 0 :(得分:4)

select s.saleID, s.eventID, s.saleTime, lp.LastPrintTime
from (
    select eventID, max(printTime) as LastPrintTime
    from print
    group by eventID
) lp
inner join sales s on lp.eventID = s.eventID 
    and saleTime > lp.LastPrintTime

答案 1 :(得分:0)

要获得上次打印时间:

SELECT MAX(p.printTime), p.eventID FROM print p

您可以在子查询中使用它来获得所需内容:

    SELECT s.saleID, s.eventID 
      FROM sales s
INNER JOIN (SELECT MAX(p.printTime) AS lastPrintTime, p.eventID 
              FROM print p
          GROUP BY p.eventID) print_time
WHERE print_time.eventID = s.eventID 
  AND s.saleTime > print_time.lastPrintTime

这有帮助吗?

答案 2 :(得分:0)

内部查询:

SELECT * FROM sales AS s INNER JOIN
(
    SELECT eventID, max(printTime) as maxPrintTime FROM [print] GROUP BY eID 
) as p ON p.eventID = s.eventIDAND s.saleTime > maxPrintTime