mysql多个左连接和分组依据的问题

时间:2012-07-03 22:48:37

标签: mysql

我有3张桌子:

TB1:

tb1_id PK
tb1_name

TB2:

tb2_id PK
tb1_id FK

TB3:

tb3_id PK
tb2_id FK

我得到了这个问题:

select a.tb1_nome
      ,b.tb2_id
      ,count(c.tb2_id) as lins 
 from tb1 a 
      left join tb2 b on a.tb1_id=b.tb1_id 
      left join tb3 c on b.tb2_id=c.tb2_id 
 group by b.tb2_id order by a.tb1_id desc

但它不会返回tb1的所有行。

2 个答案:

答案 0 :(得分:1)

  

我有3个表我需要获取与tb1匹配的所有tb2行和   显示与tb2匹配的所有tb3行的计数

我认为您只需使用INNER JOIN代替LEFT JOININNER JOIN选择在连接的表上有记录的行。尝试一下,稍后再反馈:)

SELECT  a.tb1_name,
        b.tb2_id,
        COUNT(c.tb2_id) TotalCount
FROM    tb1 a 
          INNER JOIN tb2 b
             on a.tb1_id = b.tb1_id
          INNER JOIN tb3 c
             on b.tb2_id = c.tb2_id
GROUP BY a.tb1_name, b.tb2_id
ORDER BY a.tb2_id DESC

答案 1 :(得分:0)

当你这样做时

left join tb2 b on a.tb1_id=b.tb1_id

也许你有一个错字,因为b只有tb2_id ...没有tb1_id

此外,如果您需要获取所有tb1行,即使在tb2上没有匹配结果,请考虑使用外连接。