简体   繁体   English

从相关表中获取每组的最大行数

[英]Get max row per group from a related table

This is my first time asking a question on here. 这是我第一次在这里提问。 It has been very helpful with learning. 这对学习非常有帮助。

I am trying to select a table and getting only rows that have a maximum value for its particular group in another table. 我试图选择一个表,并且只获取在另一个表中为其特定组具有最大值的行。 One of the best answers that is very close but not quite there is this one ( SQL Select only rows with Max Value on a Column ) but it only relates to a single table. 最好的答案之一是非常接近但不完全正确的答案( SQL仅选择在列上具有最大值的行 ),但它仅与单个表有关。 I have found some others with multiple table but not sure how exactly to use it. 我发现其他一些具有多个表,但不确定如何使用它。

I have a table with (simplified) 我有一张桌子(简体)

prodID, quantity, mach, etc

I then have a table with 然后我有一张桌子

prodStatusID, prodID, userID, subStatusID

a last table with sub status names 最后一个带有子状态名称的表

subStatusID, subStatusName

I am trying to get a table with all of the first table and the second table but only with the row that has the maximum status number and include the right status name. 我试图获取一个包含所有第一张表和第二张表的表,但仅包含状态号最大且包含正确状态名的行。
My other concern which may not matter now but in a year or two when this thing starts to really fill up is performance. 我现在可能并不重要的另一个问题是性能,但是在一到两年之内该问题才真正开始出现。 I dont know bad it is to have select inside a select but if I am trying to return all productions then it will be doing a query for every production. 我不知道在select中有一个select是不好的,但是如果我想返回所有产品,那么它将对每个产品进行查询。

Just to be clearer. 只是为了更清楚。 in the second table prodStatus there might be 2 rows with prodID of 4 but the subStatusID for the first one would be 1 and the second one would be 2. The userID will be different. 在第二个表prodStatus中,可能有2行,其prodID为4,但第一个表的subStatusID为1,第二个表的subStatusID为2。userID将不同。 All I want to get back is the second row because it has the highest status number and I need the userID and statusName associated with that row. 我要返回的只是第二行,因为它具有最高的状态编号,并且我需要与该行关联的userID和statusName。

I have been googling for 2 days to get this answer and I saw 1 about auctions but I just dont fully understand it even after researching it. 我已经搜寻了2天,得到了这个答案,但我看到1个关于拍卖的信息,但即使研究了一下,但我还是不完全理解。

You need to create a subquery which get the maximum value of subStatusID for each prodID . 您需要创建一个子查询,该子查询获取每个prodIDsubStatusIDprodID

SELECT  a.*,     -- select only columns that you want to show
        c.*,     -- asterisks means all columns
        d.*
FROM    table1 a
        INNER JOIN
        (
            SELECT prodID, max(subStatusID) maxID
            FROM table2
            GROUP BY prodID
        ) b ON a.prodID = b.prodID 
        INNER JOIN  table2 c
            ON b.prodID = c.prodID AND
                b.maxID = c.subStatusID
        INNER JOIN table3 d
            ON c.subStatusID = d.subStatusID

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

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