SQL表加入另一个表

时间:2011-07-11 01:07:27

标签: mysql sql

我有2个表(维护和类别表)

维护记录:

categoryCode  field2   field3

1             XXXXXX1  ACTIVE
3             XXXXXX2  ACTIVE
1             XXXXXX3  ACTIVE
1             XXXXXX4  ACTIVE
3             XXXXXX5  ACTIVE
3             XXXXXX5  NOT ACTIVE

类别表记录:

categoryCode        categoryname

1                   categoryname1
2                   categoryname2
3                   categoryname3

到目前为止,我有这个查询

  SELECT COUNT(*) AS recordcount,
         categoryCode AS catCode,
         categorytable.categoryname
    FROM maintable, 
         categorytable
   WHERE categorytable.categoryCode = maintable.categoryCode 
     AND maintable.field3 = 'ACTIVE'
GROUP BY maintable.categoryCode 
ORDER BY categorytable.categoryCode

使用以下输出

recordcount catCode categoryname
----------------------------------
3           1       categoryname1
2           3       categoryname3

但我需要一个这样的输出(包含0条记录的类别显示记录数为0):

recordcount catCode categoryname
3           1       categoryname1
0           2       categoryname2
2           3       categoryname3

2 个答案:

答案 0 :(得分:3)

SELECT 
    coalesce(COUNT(maintable.categoryCode),0) AS recordcount, 
    categorytable.categoryCode AS catCode, 
    categorytable.categoryname
FROM 
    maintable 
RIGHT JOIN categorytable ON categorytable.categoryCode = maintable.categoryCode 
GROUP BY 
    categorytable.categoryCode, 
    categorytable.categoryname 
ORDER BY 
    categorytable.categoryCode

或使用左连接

SELECT 
    coalesce(COUNT(maintable.categoryCode),0) AS recordcount, 
    categorytable.categoryCode AS catCode, 
    categorytable.categoryname
FROM 
    categorytable
LEFT JOIN maintable ON categorytable.categoryCode = maintable.categoryCode 
GROUP BY 
    categorytable.categoryCode, 
    categorytable.categoryname 
ORDER BY 
    categorytable.categoryCode

答案 1 :(得分:0)

您需要使用左连接:

SELECT COUNT(*) AS recordcount, categoryCode AS catCode, categorytable.categoryname
FROM categorytable
LEFT JOIN maintable ON categorytable.categoryCode = maintable.categoryCode 
GROUP BY maintable.categoryCode 
ORDER BY categorytable.categoryCode

如果您不想反转表名,请参阅AlexanderMP的答案。