所以我正在尝试我的第一个子查询并遇到一个小问题...为什么查询没有考虑我的WHERE子句?
我的查询:
SELECT *
FROM Product
WHERE stdUnitPrice < 5*
(SELECT MIN(stdUnitPrice)
FROM Product
WHERE discontinued = 'A')
但是在结果中我仍然在停止的列中得到的值不仅仅是'A'
结果如下:
# productId, prodName, stdUnitPrice, qtyPerUnit, discontinued
3, Aniseed Syrup, 11.00, 12 - 550 ml bottles, A
13, Konbu, 6.60, 2 kg box, A
19, Teatime Chocolate Biscuits, 10.12, 10 boxes x 12 pieces, A
21, Sir Rodney's Scones, 11.00, 24 pkgs. x 4 pieces, A
23, Tunnbrod, 9.90, 12 - 250 g pkgs., A
**24, Guarana Fantastica, 4.95, 12 - 355 ml cans, D**
33, Geitost, 2.75, 500 g, A
41, Jack's New England Clam Chowder, 10.61, 12 - 12 oz cans, A
45, Rogede sild, 10.45, 1k pkg., A
46, Spegesild, 13.20, 4 - 450 g glasses, A
47, Zaanse koeken, 10.45, 10 - 4 oz boxes, A
52, Filo Mix, 7.70, 16 - 2 kg boxes, A
54, Tourtiere, 8.19, 16 pies, A
74, Longlife Tofu, 11.00, 5 kg pkg., A
75, Rhonbrau Klosterbier, 8.52, 24 - 0.5 l bottles, A
78, Bob's Down Home Juice, 7.90, 6 pack, A
答案 0 :(得分:2)
试试这个:
select *
from Product
where stdUnitPrice < (5 * (select min(stdUnitPrice) from Product ) )
and discontinued = 'A'
答案 1 :(得分:1)
似乎MySQL正在考虑在哪里并思考stdUnitPrice < 5
同样,你需要在主要查询上。
尝试将数学移动到子查询中,如下所示:
SELECT *
FROM Product
WHERE stdUnitPrice <
(SELECT 5*MIN(stdUnitPrice)
FROM Product)
AND discontinued = 'A'
答案 2 :(得分:1)
因此,推理不能按照您希望的方式工作是因为您在第一个查询中缺少where子句。让我为你分解一下。
select * from Product where stdUnitPrice < 5* (select min(stdUnitPrice) from Product where discontinued = 'A')
所以在这个查询中首先执行子查询,所以我们假设我们将子查询设置为变量:
var subquery = select min(stdUnitPrice) from Product where discontinued = 'A';
现在执行子查询后,它会被插回到原始查询中,如下所示:(使用新的变量名称)
select * from Product where stdUnitPrice < 5 * (subquery);
所以为了让这个包含一个停止的地方='A',您需要将查询更改为以下内容:
SELECT * FROM Product WHERE stdUnitPrice < 5 * (SELECT MIN(stdUnitPrice) FROM Product WHERE discontinued = 'A') AND discontinued = 'A';
我希望这会有所帮助。
编辑:只是为了澄清你实际上不能使用像我那样的变量,只是以它为例来说明查询将如何实际执行。
答案 3 :(得分:0)
您正在执行已过滤的聚合子集操作,但是,您的主查询将返回所有行。您基本上要求返回所有行*表中的最小值。您需要返回与您的选择子句匹配的所有行中的最小值。