简体   繁体   English

MySQL-左侧联接表中的MAX

[英]MySQL - MAX in LEFT JOIN TABLE

I have hit a brick wall on this one, hopefully someone smarter than myself could point me in the right direction? 我在这上面撞上了一堵墙,希望有人比我聪明能指出正确的方向?

I have an ORDERS table containing orders (surprisingly). 我有一个包含订单的ORDERS表(令人惊讶地)。

I also have a DOWNLOADS table. 我也有一个下载表。 DOWNLOADS contains an ORDERID field, which is the ID of the order table. 下载包含一个ORDERID字段,这是订单表的ID。

DOWNLOADS has an ATTEMPT field. DOWNLOADS有一个ATTEMPT字段。 Each download creates a record in DOWNLOADS, and each record increments the value in ATTEMPT. 每个下载在DOWNLOADS中创建一个记录,每个记录在ATTEMPT中增加该值。

I just want to get the MAX value in ATTEMPT, so I can tell users what attempt they are on (or how many attempts they have left). 我只想在ATTEMPT中获得MAX值,所以我可以告诉用户他们正在进行什么尝试(或已经离开了多少次尝试)。

DOWNLOADS may or may not have any associated records in it, depending on if the user has not yet tried to download. DOWNLOADS中可能有也可能没有任何相关记录,这取决于用户是否尚未尝试下载。 Each download attempt, a record is created in DOWNLOADS. 每次下载尝试时,都会在DOWNLOADS中创建一条记录。

So in simplistic terms I am trying to do something like: 因此,以简化的方式,我正在尝试执行以下操作:

SELECT orders.*,MAX(downloads.attempt)
FROM orders
LEFT JOIN downloads on downloads.orderid = orders.id
WHERE orders.userid = '123'

Or rather, I'm trying to get all user orders, with the MAX of download attempts where any download attempts (records in DOWNLOADS) exists - or null if there are none. 或者更确切地说,我正在尝试获取所有用户订单,并在存在任何下载尝试(DOWNLOADS中的记录)的情况下使用最大下载尝试次数-如果没有,则为null。

I've been going through stackoverflow all day looking at similar examples but somehow all similar examples are massively complicated. 我整天都在研究stackoverflow,看看类似的例子,但是所有类似的例子都非常复杂。 Is there a simple (or at least elegant) way of doing this? 有没有简单(或至少优雅)的方法来做到这一点?

A bit of help would be hugely appreciated. 一点帮助将不胜感激。

Thanks. 谢谢。

Try this - 尝试这个 -

SELECT orders.userid, MAX(downloads.attempt)
FROM orders
LEFT JOIN downloads on downloads.orderid = orders.id
group by orders.userid
SELECT orders.*,MAX(downloads.attempt) FROM orders 
LEFT OUTER JOIN downloads on downloads.orderid = orders.id 
WHERE orders.userid = '123' 
GROUP BY orders.id

Try this: 尝试这个:

SELECT orders.userid,MAX(IFNULL(downloads.attempt,0))
FROM orders
LEFT JOIN downloads on downloads.orderid = orders.id
GROUP BY orders.userid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM