如何从三个没有相同id的表中读取数据

时间:2014-07-10 07:09:33

标签: sql sql-server-2008 inner-join cross-join

您好我正在使用三个表来显示客户订单信息

1. Order table(OrderId, ItemName, Description, etc...)
2. Order_Gas_Quantity(Order_gas_quantyID, OrderID, Quantity)
3. Customer_Supplying_Days(SupplyingID, CustID, SupplyingDays)

在保存客户数据的同时,我将供应日期保存到customer_Suppling_Days,在此表中我使用CustID。 表1和表1也是2具有相同的ID OrderID

我想显示今天订购的商品以及提供日期。例如,在保存客户数据的同时,如果客户选择在周一,周三,周五需要,则可以选择日期。因此,应用程序应该为今天的订单生成报告,并且项目应该在周五提供。 customer_Suppling_Days

的此表结构
`SupplyDayID    int Unchecked
CustID          int Checked
SupplyDays    nvarchar(50)  Checked

Orders

的表格结构
OrderID int Unchecked
Date    varchar(50) Checked
CName   varchar(50) Checked
CustId  int Checked
CLocation   varchar(50) Checked
Gas varchar(50) Checked
Quantity    varchar(50) Checked
VehicleNo   varchar(50) Checked
VehicleLocation varchar(50) Checked
Source  varchar(50) Checked

Order_Gas_qty

的表格结构
OrderGasQty int Unchecked
CustId  int Checked
GasName varchar(50) Checked
Quantity    varchar(50) Checked
OrderDate   varchar(50) Checked
CylinderNo  varchar(50) Checked
OrderId int Checked

1 个答案:

答案 0 :(得分:0)

您已将日期保存为varchar()格式强烈不推荐。仅以Date格式存储日期。如果您无法更改表结构,那么简单的内连接应该起作用:

select O.OrderID,
O.Date,
O.CName,
O.Gas,
O.Quantity,
O.VehicleNo,
O.VehicleLocation,
O.[Source],
OGQ.CylinderNo
from Orders O
inner join Order_Gas_qty OGQ on OGQ.OrderId = O.OrderId
inner join Customer_Supplying_Days CSD on O.CustId = CSD.CustId
where O.Date = convert( varchar(20),getdate(),101) 
-- please change the format here as per your requirement
and SupplyDayID = Day(getdate())
-- this condition also depends on data in your table