[英]Select one row for each different value of column, MySQL
Im a bit stuck and cant get my head around this MySQL. 我有点卡住,无法理解这个MySQL。 Here are my abridged tables I wish to query:
这是我希望查询的删节表:
print(printID, eventID, printTime)
print(printID,eventID,printTime)
sales(saleID, eventID, saleTime)
销售(saleID,eventID,saleTime)
I wish to get the last print time for each event, then select the sale IDs which have that eventID with a sale time greater than the last print time. 我希望获得每个活动的最后打印时间,然后选择具有该eventID且销售时间大于上次打印时间的销售ID。
I've tried loads of ways but I can't figure it. 我尝试了许多方法,但我无法理解。 Please help!
请帮忙!
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
To get the last print time: 要获得最后的打印时间:
SELECT MAX(p.printTime), p.eventID FROM print p
You can use this in a subquery to get what you need: 您可以在子查询中使用它来获得所需内容:
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
Does that help? 这有帮助吗?
Inner Query: 内部查询:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.