如何从这些表中编写SQL查询

时间:2012-02-01 14:34:22

标签: sql sql-server-2005

首先,我没有SQL开发人员。因此,我需要帮助从以下三个表中检索一些信息。

我希望namesorder dateproduct code为那些订购产品的人product code = 401.1201

如何编写SQL查询以从表中检索信息?

dbo.tblMaterial

  • MaterialId(PK,int,not null)
  • CanBeOrdered(bit,not null)
  • 名称(nvarchar(200),非null)
  • 价格(十进制(18,2),非空)
  • ProductCode(nvarchar(50),not null)

dbo.tblMaterialOrder

  • MaterialOrderId(PK,int,not null)
  • MembershipUserId(uniqueidentifyer,not null)
  • FirstName(nvarchar(50),not null)
  • LastName(nvarchar(100),not null)
  • OrderDate(datetime,not null)

dbo.tblMaterialOrderItem

  • MaterialOrderItemId(PK,int,not null)
  • MembershipUserId(uniqueidentifyer,not null)
  • ItemsCount(int,not null)
  • ItemPrice(int,not null)
  • MaterialOrder_MaterialOrderId(FK,int,not null)
  • Material_MaterialId(FK,int,not null)

我试过......

Select * From dbo.tblMaterialOrder mo Where Exists (Select MembershipUserId From
dbo.tblMaterialOrderItem Where dbo.tblMaterialOrderItem.Material_MaterialId = 
(Select MaterialId From dbo.tblMaterial Where (ProductCode = '401.1201')))

Select * from dbo.tblMaterialOrder, dbo.tblMaterialOrderItem, dbo.tblMaterial 
Where 
dbo.tblMaterialOrderItem.Material_MaterialId = '248' And 
dbo.tblMaterialOrderItem.MaterialOrder_MaterialOrderId = 
dbo.tblMaterialOrder.MaterialOrderId

没有成功。

3 个答案:

答案 0 :(得分:0)

这样的事情:

SELECT
    tblMaterial.Name,
    tblMaterialOrder.OrderDate,
    tblMaterial.ProductCode
FROM
    tblMaterial
    JOIN tblMaterialOrderItem
        ON tblMaterial.MaterialId=tblMaterialOrderItem.Material_MaterialId
    JOIN tblMaterialOrder
        ON tblMaterialOrder.MaterialOrderId=tblMaterialOrderItem.MaterialOrder_MaterialOrderId
WHERE
    tblMaterial.ProductCode='401.1201'

答案 1 :(得分:0)

SELECT 
  M.NAME
 ,M.MATERIALID
 ,O.ORDERDATE
FROM MATERIAL M
LEFT JOIN ORDERITEM OI ON M.MATERIALID = OI.MATERIAL_MATERIALID
LEFT JOIN ORDER O ON OI.MaterialOrder_MaterialOrderId = O.MaterialOrderId
WHERE M.MATERIALID = '401.1201'

答案 2 :(得分:0)

试试这个未经测试的Skript:

select a.name, b.orderdate, a.productcode 
from tblMaterial a left outer join tblMaterialOrderItem b 
on a.MaterialId = b.Material_MaterialId 
left outer join tblMaterialOrder c 
on c.MaterialOrder_MaterialOrderId = b.MaterialOrderId
where a.productcode = '401.1201'