简体   繁体   English

SQL获取按第二个ID分组的最大ID

[英]SQL Get max ID grouped by a second ID

I am working on a php/mysql best before date checking system and upon creating a new check I need the system to find a best before date for a certain product by looking for it most recent closed check 我正在使用php / mysql最好的日期前检查系统,并且在创建新支票后,我需要系统通过查找最新的封闭式检查来为某个产品找到最佳的日期。

I am working with a few tables to get this done: 我正在处理一些表格以完成此操作:

bbcheckProducts    
ID checkID productID checked bestBefore
 1       1         1       1 2015-05-06
 2       2         1       1 2016-07-22
 3       3         1       1 2016-09-16

bbChecks
checkID userID closed
      1      1      1
      2      2      1
      3      1      1

So when I run this query on the tables in the image above: 因此,当我在上图中的表上运行此查询时:

SELECT  ID,
        MAX(checkID) AS maxCheck,
        bestBefore
FROM    bbcheckProducts
WHERE   checkID IN 
(
    SELECT  checkID
    FROM    bbChecks
    WHERE   userID = 1
    AND     closed = 1
)
AND     checked = 1
GROUP BY productID
ORDER BY bestbefore ASC

it returns something like this: 它返回如下内容:

ID = 1
maxCheck = 3
bestBefore = 2015-05-06

so it does take the max checkID but the other values remain equal to the first occurence of productID. 因此它确实采用了最大的checkID,但其他值仍等于第一次出现的productID。 I want it to take the values that go together with that max ID so the result would look like this: 我希望它采用与该最大ID一起使用的值,因此结果应如下所示:

ID=3
maxCheck = 3
bestBefore = 2016-09-16

so how do I get my query to work like that? 那么如何使查询像这样工作?

NOTE: there are multiple products so product one may be in check 1 and 3 while product 2 is only in 1 so it has to take the data of product 2 from check 1 and the data of product 1 from check 3 注意:有多个产品,因此产品1可能在检查1和3中,而产品2仅在检查1中,因此它必须从检查1获取产品2的数据,并从检查3获取产品1的数据。

您需要在第二张表上使用max函数,例如此查询

select * from table_name where some_colomn = 'some_value' and some_colomn in (select max(some_colomn) from table_name2 where some_col = 'some_value' group by some_colomn)

You could join your tables to get a reduced set of all record with an check_ID existing in your bbChecks -table. 你可以加入你的表得到一组简化的所有记录与check_ID在现有bbChecks -表。 Then you can run your max(CheckID) -selection on the reduced set. 然后,可以对精简集运行max(CheckID)

In your case this would like like that: 您的情况如下:

SELECT ID, max(checkID), bestBefore
FROM bbcheckProducts p
INNER JOIN bbChecks c ON (p.checkID = c.checkID)
WHERE UserID = 1
AND closed = 1
AND checked = 1

This returns you first of alle the records with the checkIDs 1 and 3. And then you select the max(checkID), so it returns you the checkID 3. 这将首先向您返回带有checkID 1和3的记录。然后选择max(checkID),因此它会向您返回checkID 3。

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

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