我有3张这样的表:
CREATE table materials
(id serial primary key not null,
name varchar(50) not null,
unit varchar(10) not null default 'шт',
price decimal(12, 2) not null check (price>0));
CREATE table warehouses
(id serial primary key not null,
lastname varchar(25) not null);
CREATE table materials_in_warehouses
(id_warehouses integer references warehouses(id) on update cascade on delete cascade,
id_materials integer references materials(id),
unit varchar(15) default 'шт',
count integer not null CHECK (count>0),
lastdate date not null,
primary key (id_warehouses, id_materials);
我需要选择价格为>的所有材料。 200,这样: 在每个仓库中,该材料的数量> 100。
问题在于我们必须使用这种材料装配所有仓库,而不是任何一种。我没有想法。
例如,我有:
materials
id name price unit
--- ------ ----- -----
3 Silver 300 kg
warehouses
id lastname
---- ---------
2 Forman
3 Tramp
materials_in_warehouses
id_materials id_warehouses count lastdate
------------ ------------- ----- --------
3 3 300 2015-12-20
3 2 200 2015-12-20
...我希望在我的结果中看到Silver,但是如果我添加到table materials_in_warehouses,其中count是< 100,因此,银不应该。
这是我的示例查询,但它不适合条件
select materials.name
, materials.price
, materials.unit
from materials
, materials_in_warehouses
where price > 200
AND id = id_materials
AND count > 100;
答案 0 :(得分:0)
您可以使用以下子查询解决此问题:
第一种情况,计数>每个仓库100个
SELECT * FROM materials WHERE id IN (
SELECT m.id FROM
materials_in_warehouses AS mw INNER JOIN
materials AS m ON (m.id = mw.id_materials)
WHERE
m.price > 200 AND
mw.count > 100
GROUP BY id
HAVING COUNT(*) = (SELECT COUNT(*) FROM warehouses)
);
第二种情况,所有仓库数量的总和> 100
SELECT * FROM materials WHERE id IN (
SELECT m.id FROM
materials_in_warehouses AS mw INNER JOIN
materials AS m ON (m.id = mw.id_materials)
WHERE
m.price > 200
GROUP BY id
HAVING SUM(mw.count) > 100
);
好的,第三种情况,所有材料的价格>每个仓库中200 AND 计数> 100
SELECT m.* FROM
materials_in_warehouses AS mw INNER JOIN
materials AS m ON (m.id = mw.id_materials)
WHERE
m.price > 200 AND
mw.count > 100
GROUP BY id
尽可能简单
答案 1 :(得分:0)
您需要首先加入表格并建立关系。
SELECT
w.lastname
, m.name
, m.price
, miw.count
FROM materials m
INNER JOIN materials_in_warehouses miw
ON m.id = miw.id_materials
INNER JOIN warehouses w
ON w.id = miw.id_warehouses
从那里,你可以添加where子句来定位你想要的数据。
WHERE m.price >= 200
AND miw.count > 100
ORDER也有帮助,但只能查看结果。
ORDER BY w.lastname, m.name
如果您仍然缺少此时希望看到的记录,则可能是数据问题(您没有在MIW表中定义仓库,或者材料表中缺少材料)。
编辑:如果您考虑上述问题中的数据,并添加更改仓库2的MIW行计数为50,那么将排除该行。您仍会在结果中看到Silver,因为它以您所寻找的数量存在于仓库3中。
答案 2 :(得分:0)
试试这个
select * from materials
inner join materials_in_warehouses on materials.id = materials_in_warehouses.id_materials
where count>100 and price >200