需要帮助结合两个MySQL查询

时间:2014-01-05 23:39:39

标签: mysql sql

我对SQL并不陌生,也无法弄清楚如何做到这一点。以下是我目前的两个问题。

SELECT TicketID_PK, SubProjectID_FK, ProjectID_FK, CustomerID_FK, TicketDate, TicketNumber, 
SignOff, WorkOrder, ClientPO, TicketType, Description, Processed 
FROM Tickets 
INNER JOIN CustomersSubProjects ON Tickets.SubProjectID_FK = CustomersSubProjects.SubProjectID_PK 
INNER JOIN CustomersProjects ON CustomersSubProjects.ProjectID_FK = CustomersProjects.ProjectID_PK 
WHERE TicketID_PK = 1

SELECT ROUND(WCB+Vacation+Stat+UIC+CPP+Overhead,2) AS Total 
FROM EmployeeFormula 
WHERE EffectiveDate <= $TicketDate
ORDER BY EffectiveDate DESC LIMIT 1

我将TicketDate保存为$ TicketDate并在第二个查询中使用它,但我确信有一种方法可以将两个查询组合起来以避免这种情况。任何帮助将不胜感激。

编辑:我需要通过比较TicketDate列(在Tickets表中)和EffectiveDate列来选择EmployeeFormula Total(如第二个查询中所示)。所以结果应该是这样的:

TicketID_PK     SubProjectID_FK     ProjectID_FK    CustomerID_FK   TicketDate  TicketNumber    Total
1   1   1   1   2014-01-05  1-0501-00   30.78

1 个答案:

答案 0 :(得分:0)

像子查询一样使用。

SELECT TicketID_PK, SubProjectID_FK, ProjectID_FK, CustomerID_FK, TicketDate, TicketNumber, 
SignOff, WorkOrder, ClientPO, TicketType, Description, Processed, (SELECT ROUND(WCB+Vacation+Stat+UIC+CPP+Overhead,2) FROM EmployeeFormula WHERE EffectiveDate <= TicketDate ORDER BY EffectiveDate DESC LIMIT 1) AS Total
FROM Tickets 
INNER JOIN CustomersSubProjects ON Tickets.SubProjectID_FK = CustomersSubProjects.SubProjectID_PK 
INNER JOIN CustomersProjects ON CustomersSubProjects.ProjectID_FK = CustomersProjects.ProjectID_PK 
WHERE TicketID_PK = 1