【问题标题】:Subquery returns different values for 2 almost identical queries子查询为 2 个几乎相同的查询返回不同的值
【发布时间】:2014-12-18 16:40:09
【问题描述】:

我对以下查询及其返回值感到困惑。为什么在子查询中定义recipe r时只返回一个值,而在主查询中定义recipe r时返回20个值?造成这种差异的原因是什么?

第一个查询:

SELECT   pizza, ingredient, amount 
FROM     recipe 
WHERE    amount = 
         (      SELECT Max(amount) 
                FROM   recipe r
                WHERE  ingredient=r.ingredient) 
ORDER BY ingredient;

  pizza  | ingredient | amount  
---------+------------+--------  
 seafood | seafood    |    200

第二次查询:

SELECT   pizza, ingredient, amount 
FROM     recipe r 
WHERE    amount= 
         (      SELECT max(amount) 
                FROM   recipe 
                WHERE  ingredient=r.ingredient) 
ORDER BY ingredient;

   pizza    | ingredient | amount  
------------+------------+--------   
 napolitana | anchovies  |    100
 special    | bacon      |     25
 cabanossi  | cabanossi  |    150
 siciliano  | capsicum   |     75
 mexicano   | capsicum   |     75
 margarita  | cheese     |    120
 mexicano   | chilli     |     25
 special    | egg        |     25
 garlic     | garlic     |     25
 ham        | ham        |    150
 mushroom   | mushroom   |    100
 napolitana | olives     |     75
 mexicano   | onion      |     75
 vegetarian | peas       |     50
 americano  | pepperoni  |     75
 hawaiian   | pineapple  |    100
 americano  | salami     |    120
 seafood    | seafood    |    200
 mexicano   | spice      |     20
 vegetarian | tomato     |     50

【问题讨论】:

  • 您还应该选择您正在使用的数据库并适当地标记问题。我正在删除特定的数据库标签并用“sql”替换它们。
  • 非常感谢!这是我第一次发布问题,下次尝试做得更好。 :P

标签: mysql sql-server sql-server-2008 postgresql subquery


【解决方案1】:

您的两个查询是:

select pizza, ingredient, amount
from recipe
where amount = (select max(amount)
                from recipe r
                where ingredient = r.ingredient
               )
order by ingredient;

和:

select pizza, ingredient, amount
from recipe r
where amount = (select max(amount)
                from recipe
                where ingredient = r.ingredient
                )
order by ingredient;

这两者都被称为相关子查询。但是,第一个是不相关的。条件:

                where ingredient = r.ingredient

ingredient 的两个引用都指向内部查询中的表。所以,这基本上是一个空操作。更具体地说,它完全等同于where r.ingredient is not null。此内部查询返回单个值,即表中 amount 的最大值。

第二个版本是相关的,因此它返回每种成分的最大量。

完全限定所有表名是一个很好的规则。您想要的查询应如下所示:

select r.pizza, r.ingredient, r.amount
from recipe r
where r.amount = (select max(r2.amount)
                  from recipe r2
                  where r2.ingredient = r.ingredient
                 )
order by r.ingredient;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多