mysql查询不起作用

时间:2014-03-27 11:18:25

标签: mysql sql

这是我的mysql查询!

SELECT projects.projects_id, 
       projects.projects_title,
       projects.projects_cost
  FROM projects
       LEFT JOIN invoice
           ON invoice.projects_id = projects.projects_id
       LEFT JOIN project_assign
           ON project_assign.projects_id=projects.projects_id
 WHERE project_assign.assigned_user_id=3 
       AND (SUM( invoice.invoice_amount) < projects.projects_cost 
            OR invoice.projects_id is null )
       AND project_assign.project_completed_date IS NOT NULL

在此查询中,我想要选择所有行:

  
      
  1. 不存在于其他表格中,例如(在我的情况下,其他表是   &#34;发票&#34;)
  2.   
  3. 或者如果持续,则此条件必须保持sum(invoice.invoice_amount) < projects.projects_cost
  4.   

感谢。

3 个答案:

答案 0 :(得分:0)

select projects.projects_id, projects.projects_title,projects.projects_cost
 from projects
left join invoice
on invoice.projects_id = projects.projects_id
left join project_assign
on project_assign.projects_id=projects.projects_id
where project_assign.assigned_user_id=3 and
 ((select sum(invoice.invoice_amount) from invoice) < projects.projects_cost or invoice.projects_id is null )
and project_assign.project_completed_date is not null 

答案 1 :(得分:0)

您不能将聚合函数放在where子句中。在这种情况下,您可以使用子查询进行聚合,然后进行比较:

SELECT p.projects_id, p.projects_title, p.projects_cost
FROM projects p LEFT JOIN
     (select i.projects_id, sum(invoice_amount) as invoice_amount
      from invoice i
     ) i
     ON i.projects_id = p.projects_id LEFT JOIN
     project_assign pa
     ON pa.projects_id = p.projects_id
 WHERE pa.assigned_user_id = 3 AND
       (i.invoice_amount < p.projects_cost OR i.projects_id is null ) AND
       pa.project_completed_date IS NOT NULL;

答案 2 :(得分:0)

分开你的问题。使用UNION。首先使用一个查询来选择第一个表中不存在的所有记录(使用LEFT JOIN),与第二个查询的结果联合,这将为您提供满足第二个条件的所有记录(使用外连接)

//Select all records present in left table
//union
//select all records present in both tables matching your condition.

    SELECT projects.projects_id, 
       projects.projects_title,
       projects.projects_cost
  FROM projects
       LEFT JOIN invoice
           ON invoice.projects_id = projects.projects_id
       LEFT JOIN project_assign
           ON project_assign.projects_id=projects.projects_id
  WHERE project_assign.assigned_user_id=3  
  AND project_assign.project_completed_date IS NOT NULL 
    UNION
   SELECT projects.projects_id, 
       projects.projects_title,
       projects.projects_cost
  FROM projects
       INNER JOIN invoice
           ON invoice.projects_id = projects.projects_id
       INNER JOIN project_assign
           ON project_assign.projects_id=projects.projects_id
  WHERE project_assign.assigned_user_id=3 
   AND (SUM( invoice.invoice_amount) < projects.projects_cost  
  AND project_assign.project_completed_date IS NOT NULL