加入3个表

时间:2011-07-11 11:04:23

标签: mysql

我有3个表(CompanyProfile,IndustryTable,MainTable)

公司简介

CompanyCode      CompanyName      IndustryCode
AAAA             Company A        3
BBBB             Company B        1
CCCC             Company C        4
DDDD             Company D        1
EEEE             Company E        1
GGGG             Company F        2

IndustryTable

IndustryCode     IndustryName     status
1                Manufacturing    ACTIVE
2                Sales            ACTIVE
3                Logistics        ACTIVE
4                Energy           DEACTIVATED

MainTable

CompanyCode  field2
AAAAA        SampleRecord1
AAAAA        SampleRecord2
DDDDD        SampleRecord3
CCCCC        SampleRecord4
EEEEE        SampleRecord5

现在我需要一个查询来从 MainTable 分组获取所有RecordCount IndustryTable.IndustryCode(仅限ACTIVE),所以上面的示例应该给出以下输出

IndustryCode     IndustryName     RecordCount    (Explanation)
1                Manufacturing    2              -Record 3 and 5
2                Sales            0              
3                Logistics        2              -Record 1 and 2

记录4(CCCCC)将不会显示,因为IndustryTable.IndustryCode 4已被停用

1 个答案:

答案 0 :(得分:0)

这样的东西

select industrycode, industryname, count(*) as total from companyprofile t1 join industry table t2 join maintable t3 where t1.companycode=t3.companycode and t1.industrycode=t2.industrycode and t2.status="ACTIVE" group by industrycode