多表SQL SELECT语句

时间:2017-06-14 13:44:42

标签: mysql sql phpmyadmin

我试图从两个表(存档和项目如下所示)中获得结果,这两个表具有来自两个不同表的规定。我们希望从归档和项目(具有完全相同的字段)中获取Designer,ProjectNum和总金额。存档和项目有一个名为customerEmail的字段,我想用它来排除另一个名为profiles(作为customerEmail)的表,其中customerStatus为“Canceled”。我还希望从另一个名为changeorder的表中获取change_total,该表具有与归档和项目相同的ProjectNum。

我首先使用UNION来获取项目和存档,然后添加代码以取消已取消“已取消”的项目

 SELECT DISTINCT(designerName), 
        SUM(total), 
        SUM(amount) 
 FROM
 (
   SELECT DISTINCT(Building_designer) as designerName, 
          COUNT(DISTINCT(Project_Num))as total, 
          SUM(archive.total_amount) as amount 
   FROM `archive` 
   INNER JOIN profiles
     ON archive.customer_email = profiles.customer_email 
   WHERE profiles.customer_status != "Cancelled" 
   AND SUBSTRING(archive.Project_Num,1,2)=17 
   GROUP BY designerName 

   UNION 

   SELECT DISTINCT(Building_designer) as designerName, 
          COUNT(DISTINCT(Project_Num))AS total, 
          SUM(projects.total_amount) AS amount
   FROM `projects` 
   INNER JOIN profiles 
     ON projects.customer_email = profiles.customer_email 
   WHERE profiles.customer_status != "Cancelled" 
   AND SUBSTRING(projects.Project_Num,1,2)=17 
   GROUP BY designerName
 ) AS temp 
 GROUP BY designerName

我试图从名为changeorder的表中获取totalAMOUNT。是否最好再做一次加入以包括表格?

以下是一个在没有将其添加到此声明的情况下工作的示例

SELECT SUM(DISTINCT(change_total))
FROM `changeorder` 
WHERE SUBSTRING(project_num,1,2)=17

为什么我需要添加其他两个表,它还会跟踪“已取消”的内容。所以我需要将与每个人相关的所有项目编号的change_total进行总结

1 个答案:

答案 0 :(得分:1)

当心。我从" Hello World"开始编码不到两个月前。

如果我理解正确,你就会找三套'数据的: 1)存档中的Designer,ProjectNum和total_amount 2)来自项目的Designer,ProjectNum和total_amount 3)change_total from changeorder

您希望从前两个消除客户状态被取消的任何情况(在另一个表中)。

如果这一切都正确,请尝试:

SELECT a.Designer, a.ProjectNum, a.total_amount, 
        prjct.Designer, prjct.ProjectNum, prjct.total_amount,
        chgOrd.change_total
    -- the first two JOINs are to enable the WHERE later for knocking out
FROM archive a JOIN profiles prf ON a.customerEmail = prf.customerEmail, 
              projects prjct JOIN profiles prf ON prjct.customerEmail = prf.customerEmail
    -- then another (double) JOIN to link changeorder properly to archive and project
              changeorder chgOrd JOIN a ON chgOrd.ProjectNum = a.ProjectNum
                                  JOIN prjct ON chgOrd.ProjectNum = prjct.ProjectNum
 WHERE prf.customerStatus <> "Cancelled"

我希望我能够使用在结尾处JOIN中FROM开头创建的别名。