【发布时间】:2016-01-05 10:18:49
【问题描述】:
我有一个sql语句已经可以了,但我认为一定有比我更好的解决方案。
我正在尝试获取最高价从未售出的文章。
通过此选择,我将获得所有尚未售出的文章(数量 + 价格):
select anr, price
from article a
where not exists(
select 1 from OrderItems o
where o.artnr = a.anr
)
货号+价格结果的样子
| Anr | Price |
| 1 | 300.0 |
| 4 | 340.0 |
| 5 | 340.0 |
| 3 | 200.0 |
我获得最高价格文章的临时解决方案是:
select anr, price
from article
where anr in(
select anr
from article a
where not exists(
select 1 from OrderItems o
where o.artnr = a.anr
)
)
and price = (
select max(price)
from article a
where not exists(
select 1 from OrderItems o
where o.artnr = a.anr
)
)
正确的解决方法是:
| Anr | Price |
| 4 | 340.0 |
| 5 | 340.0 |
有没有办法避免两次相同的子选择?
这里的测试是带有我插入值的缩短的 Create Table 脚本:
CREATE TABLE Article
(
Anr Int Primary Key,
Price Numeric(9,2) Not Null
);
CREATE TABLE Orders
(
OrderNr Int Primary Key
)
CREATE TABLE OrderItems
(
OrderNr Int References Orders On Delete Cascade,
ItemNr Int,
Artnr Int References Article Not Null,
Amount Int Not Null Check(Amount >= 0),
Primary Key(OrderNr, ItemNr)
)
-- articles without an order
Insert into Article (Anr, Price) values(1,300.0);
Insert into Article (Anr, Price) values(4,340.0);
Insert into Article (Anr, Price) values(5,340.0);
Insert into Article (Anr, Price) values(3,200.0);
-- articles for order with orderNr '1'
Insert into Article (Anr, Price) values(2,340.0);
Insert into Article (Anr, Price) values(6,620.0);
-- insert test order that contains the two articles
Insert into Orders (OrderNr) values (1);
Insert into OrderItems(OrderNr, ItemNr, Artnr, Amount) values(1,1,2,4);
Insert into OrderItems(OrderNr, ItemNr, Artnr, Amount) values(1,2,6,2);
我也看了题目Select max value in subquery SQL 但我认为在我的情况下必须有一种更短的方式来进行选择。
【问题讨论】:
-
SQL Server/MySQL/Oracle/Postgresql/Firebird/SQLite?
-
它应该适用于每个数据库,这就是我不想要特定数据库的原因。我想通过使用标准 sql 来解决这个问题。但我正在 Oracle 12c 上进行测试 :)
-
如果你添加脚本来创建表和记录..我可以帮助你