简体   繁体   中英

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

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. I want it to take the values that go together with that max ID so the result would look like this:

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

您需要在第二张表上使用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. Then you can run your max(CheckID) -selection on the reduced set.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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