需要帮助编写SQL连接查询

时间:2013-09-19 23:35:41

标签: mysql sql sql-server

我有一个名为“customer_requests”的表:

[CustomerRequestID] 
[Title] 
[Description] 
[RFQDate] 
[Q2CDate] 
[QuantityRequested] 
[GST] 
[NetCost] 
[Markup] 
[NetSellPrice] 
[GrossSellPrice] 
[fkCustomerID] 
[Status]

一张名为“工作”的表格:

[JobID] 
[JobTitle] 
[Description] 
[fkCustomerRequestID] 
[fkSupplierID] 
[fkSupplierQuoteID] 
[Quantity] 
[Cost] 
[Status] 
[ETA] 
[LoggedBy] 
[DeliveryAddress] 
[ParentJobID]

我想编写一个select查询,从两个表中选择所有条目,并在下表中显示它们:

[QuoteNumber] (refers to CustomerRequestID in customer_requests, and fkCustomerRequestID in job)

[JobNumber] (refers to JobID in job, and is blank if the entry is from customer_requests)

[CustomerName] (selected using fkCustomerID in customer_requests, selected using fkCustomerRequestID->fkCustomerID in job)

[SupplierName] (selected using fkSupplierID in job, blank if entry is from customer_requests)

[JobTitle] (refers to title in customer_requests, and JobTitle in job)

[Quantity] (refers to QuantityRequested in customer_requests, and Quantity in Job)

[Cost]  (refers to GrossSellPrice in customer_requests and Cost in Job)

[ETA] (refers to ETA in Job, and blank if the entry is from customer_requests)

[Status] (refers to Status in customer_requests, and Status in Job)

我如何将这两者结合起来制作这张表?

1 个答案:

答案 0 :(得分:2)

我假设您还有表供应商和客户:

INSERT INTO NEWTABLENAME
SELECT j.fkCustomerRequestID,
    j.JobID,
    c.CustomerName,
    s.supplierName,
    j.JobTitle,
    j.Quantity,
    j.Cost,
    j.ETA,
    j.STATUS
FROM Jobs j
INNER JOIN supplier s ON j.fkSupplierID = s.SupplierID
INNER JOIN customer c ON j.fkCustomerRequestID = c.customerID

编辑:

如果您想要来自两个表的所有信息,您可以使用以下查询执行上述查询,然后执行UINON ALL:

SELECT cr.fkCustomerRequestID,
    "",
    c.CustomerName,
    "",
    cr.title,
    cr.QuantityRequested,
    cr.GrossSellPrice,
    "",
    cr.STATUS
FROM Jobs customer_requests
INNER JOIN customer c ON cr.fkCustomerID = c.customerID