SQL加入问题

时间:2016-01-29 12:28:25

标签: mysql sql

我有3张桌子:

enter image description here

到目前为止我已尝试过这个:

SQLSTATE[42S22]: Column not found: 1054 Unknown     column'
amount_repositories.report_merchant_transactions_id' 
in 'where     clause' 
(SQL: select * from `amount_repositories` where 
    `amount_repositories`.`report_merchant_transactions_id` = 1 and 
`amount_repositories`.`report_merchant_transactions_id` is not null)

这不起作用,因为我需要连接到另一个表:

  

部门

我怎么能有另一个子查询?

任何解决方案?我正在使用的MySQL

3 个答案:

答案 0 :(得分:1)

您可以使用cross join生成所有行,然后引入现有结果(如果有)进行聚合:

select d.c_id, d.D_id, p.P_id, count(ul.c_id) as cnt
from comp_prod p cross join
     departments d left join
     user_logs ul
     on ul.c_id = d.c_id and ul.d_id = d.d_id and ul.p_id = p.p_id
group by d.c_id, d.D_id, p.P_id;

答案 1 :(得分:1)

希望这有帮助

select 
      sub.C_id,sub.D_id,sub.P_id,count(Userlogs.D_id) 
from 
      (select Comp_prod.C_id,D_id,P_id from Comp_prod join Departments on 
       Comp_prod.C_id = Departments.C_id ORDER by Comp_prod.C_id asc, 
       Departments.D_id ASC, Comp_prod.P_id ASC) as sub 
   left join Userlogs 
      on 
          sub.C_id = Userlogs.C_id and sub.D_id = Userlogs.D_id  
          and sub.P_id = Userlogs.P_id 
group by 
      sub.C_id,sub.D_id,sub.P_id

答案 2 :(得分:1)

comp_prod和C_id上的部门之间的正常内部联接将为您提供这些内容的每个组合(您可以在WHERE子句中将其缩小到C_id为15),然后LEFT OUTER JOIN user_logs以获得匹配的内容。使用COUNT(C_id),以便计算找到匹配项的行数(即,C_id不为空)

SELECT Comp_prod.C_id,
        Departments.D_id,
        Comp_prod.P_id,
        COUNT(Userlogs.C_id)
FROM Comp_prod
INNER JOIN Departments
ON Comp_prod.C_id = Departments.C_id
LEFT OUTER JOIN Userlogs
ON Comp_prod.C_id = Userlogs.C_id
AND Comp_prod.P_id = Userlogs.P_id
AND Departments.D_id = Userlogs.D_id
WHERE Comp_prod.C_id = 15
GROUP BY Comp_prod.C_id,
        Departments.D_id,
        Comp_prod.P_id