嵌套SELECT返回多个记录

时间:2018-03-23 05:17:58

标签: mysql sql database

我想返回记录被标记为有效的转移金额= 1且日期最大。

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

完美运作并返回' 2018-03-20 12:00:00'应该如此。

然而,当我把它嵌入另一个选择中时,我得到了两条记录; 1800我期望和1500哪个记录有最大日期但是不活动的记录...

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))

数据如下

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               

任何人都可以帮我解决我做错的事吗?有没有办法在不创建临时表和更新代码的情况下执行此操作?

由于

3 个答案:

答案 0 :(得分:0)

您的第二个版本的查询正在按预期工作。

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

但是,你也可以通过相关方法

来做到这一点
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)

但是,您无需在brew_id casue中subquery过滤outer query已在brew_id上应用了过滤器。

答案 1 :(得分:0)

来自您的第一个查询

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

你提到的2018-03-20 12:00:00正如你所提到的那样。 现在您要插入第二个查询:

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

根据此查询,您得到了正确的结果,因为您没有提到您希望在第二个查询中记录where active = 1

答案:

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

答案 2 :(得分:-1)

尝试始终包含针对所有列引用的相关表名或别名。

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)
      )