简体   繁体   English

SQL 表加入另一个表

[英]SQL Table Joining Another Table

I have 2 Tables (maintable and categorytable)我有 2 个表(maintable 和 categorytable)

maintable records:主表记录:

categoryCode  field2   field3

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

categorytable records:类别表记录:

categoryCode        categoryname

1                   categoryname1
2                   categoryname2
3                   categoryname3

So far I have this query到目前为止,我有这个查询

  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

with the following output与以下 output

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

But I need an output something like this (Categories with 0 records included showing a recordcount of 0):但我需要一个类似这样的 output (包含 0 条记录的类别显示记录数为 0):

recordcount catCode categoryname
3           1       categoryname1
0           2       categoryname2
2           3       categoryname3
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

or, with a left join或者,使用左连接

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

You need to use a left join:您需要使用左连接:

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

If you don't want to reverse the table names see AlexanderMP's answer.如果您不想反转表名,请参阅 AlexanderMP 的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM