我正在尝试使用Where-In子句从不同表的列中检索数据,但无法这样做。必需的任务是:“列表名称,包装重量和生产的单位以及所有已过期产品的批号”
数据库看起来像这样
create table Products(
ProductId int,
ProductName varchar(20) not null,
PackageWeight float not null,
PricePerUnit int not null,
AmountInStore int,
Primary Key(ProductId)
)
insert into Products values(1, 'Chicken Cutlet', 0.5, 500, 600)
insert into Products values(2, 'Chicken Cutlet', 0.25, 250, 0)
insert into Products values(3, 'Chicken Cutlet', 1, 1000, 500)
insert into Products values(4, 'Chicken Cutlet', 5, 4500, 600)
insert into Products values(5, 'Chicken Tenders', 300, 500, 500)
insert into Products values(6, 'Chicken Tenders', 600, 500, 100)
insert into Products values(7, 'Potato Fries', 1, 150, 0)
insert into Products values(8, 'Potato Fries', 5, 750, 800)
create table Production(
ProductId int,
BatchNo char(6) ,
UnitsProduced int not null,
DateOfProduction date not null,
ExpiryDate date not null,
Foreign Key(ProductId) references Products(ProductId),
Primary Key(ProductId, BatchNo)
)
insert into Production values(1, '1-1001', 1000, '2014-01-01', '2014-01-10')
insert into Production values(2, '1-1001', 1000, '2014-01-01', '2014-01-10')
insert into Production values(3, '1-1001', 1000, '2014-02-01', '2014-02-10')
insert into Production values(4, '1-2001', 500, '2014-05-01', '2014-10-30')
insert into Production values(5, '1-2001', 500, '2014-05-10', '2030-11-10')
到目前为止,我有这个:
select ProductName, PackageWeight from Products where ProductId in(
select ProductId from Products
Intersect
select ProductId from Production where ExpiryDate < GETDATE())
我得到正确的产品名称和包装重量,因为它们都来自同一表即产品,但是我又如何从不同表即同一生产中检索BatchNo
,UnitsProduced
查询?
答案 0 :(得分:0)
您需要基于join
ProductId
表,尝试像下面的查询。
如果要修改您现有的查询,应该是这样。
SELECT productname,
packageweight,
prdn.batchno,
prdn.unitsproduced
FROM products prd
INNER JOIN production prdn
ON prd.productid = prdn.productid
WHERE prd.productid IN(SELECT productid
FROM products
INTERSECT
SELECT productid
FROM production
WHERE expirydate < Getdate())
但是,如果需要,您可以像下面这样重构查询。
SELECT productname,
packageweight,
prdn.batchno,
prdn.unitsproduced
FROM products prd
INNER JOIN production prdn
ON prd.productid = prdn.productid
WHERE expirydate < Getdate()
答案 1 :(得分:0)
我只会使用JOIN
:
SELECT P.ProductName, P.PackageWeight, PD.BatchNo, PD.UnitsProduced
FROM Products P
JOIN Production PD ON P.ProductId = PD.ProductId
WHERE ExpiryDate < CONVERT(DATE,GETDATE())
答案 2 :(得分:0)
您可以使用sql server views
轻松实现这一目标。
这是您的操作方法:
创建视图
-- Note that Table Alias is Used For Query Clarity
-- 'P' => For Product Table
-- 'Pr' => For Production Table
CREATE VIEW viewName
AS
SELECT P.ProductId AS ID,
P.ProductName AS Name,
P.PackageWeight,
P.PricePerUnit,
P.AmountInStore,
Pr.BatchNo,
Pr.ExpiryDate,
Pr.UnitsProduced,
Pr.DateOfProduction
FROM Production AS Pr
INNER JOIN
Products AS P
ON Pr.ProductId = P.ProductId;
获得结果如下
SELECT Name,
PackageWeight,
BatchNo,
UnitsProduced
FROM viewName
WHERE ExpiryDate < GETDATE();