简体   繁体   中英

Nested SELECT returning more than one record

I want to return the transfer amount where the record is marked as active = 1 and the date is the greatest.

SELECT 
    MAX(transfer_date)
FROM
    brew_transfer
WHERE
    brew_id = 20 AND active = 1

works perfectly and returns '2018-03-20 12:00:00' as it should.

However when I nest it inside another select I am getting two records returned; 1800 which I expect and 1500 which record has the max date but for an inactive record...

SELECT 
    brew_transfer.transfer_amount
FROM
    brew_transfer
WHERE
    transfer_date = (SELECT 
        MAX(transfer_date)
    FROM
        brew_transfer
    WHERE
        (brew_id = 20 AND active = 1))

Data is as below

brew_transfer_id active brew_id status_id transfer_date transfer_amount 
        16         0       20       4       2018-03-22        1500              
        19         1       20       2       2018-03-18        1850              
        20         1       20       3       2018-03-20        1800               

Can anyone help me with what I am doing wrong? Is there a way to do this without creating a temp table and some update code?

Thanks

Your second version of query is working as you expect.

select * from brew_transfer t
where transfer_date  = (select max(transfer_date) 
                        from brew_transfer where brew_id = 20 AND active = 1)

However, you could also do that via correlate approach

select * from brew_transfer t
where brew_id = 20 and transfer_date = (
      select max(transfer_date) from brew_transfer 
      where brew_id = t.brew_id and active = 1)

However, you don't need to filter brew_id in subquery casue outer query has already applied filter on brew_id .

From your first query which is

SELECT 
    MAX(transfer_date)
FROM
    brew_transfer
WHERE
    brew_id = 20 AND active = 1

You are getting 2018-03-20 12:00:00 as you mentioned. Now you are inserting in the second query which make it:

SELECT 
    brew_transfer.transfer_amount
FROM
    brew_transfer
WHERE
    transfer_date = 2018-03-20 12:00:00)

According to this query you are getting right result as you don't mentioned that you want record where active = 1 in second query

Answer:

SELECT 
    brew_transfer.transfer_amount
FROM
    brew_transfer
WHERE
    (brew_id = 20 AND active = 1) 
ORDER BY 
    transfer_date 
DESC LIMIT 1;

Try always including relevant table names or aliases against ALL column references.

SELECT
      brew_transfer.transfer_amount
FROM brew_transfer
WHERE brew_transfer.transfer_date = (
      SELECT
            MAX(bt.transfer_date)
      FROM brew_transfer bt
      WHERE (bt.brew_id = 20
      AND bt.active = 1)
      )

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