sql计算m / n关系中的多个列

时间:2014-02-01 15:52:31

标签: mysql sql

我正在努力处理三个相关的表格,我希望显示域数地址数使用某个代码。我有三张桌子:

table_locations

ID | domain       | address             
======================================
 1 | example.com  | example.com/siteA   
 2 | example.com  | example.com/siteB   
 3 | example.com  | sub.example.com     
 4 | whatever.com | whatever.com 
 5 | foobar.com   | foobar.com/site123  
 6 | foobar.com   | foobar.com/site     

table_codes

ID | code        
==========
 1 | ABC 
 2 | DEF  

table_codes_locations

code_id | location_id        
=====================
 1      | 1 
 1      | 2    
 1      | 3
 1      | 4
 2      | 5 
 2      | 6 

我想得到什么(编辑:将查询限制为address ='example.com'):

ID | code  | domaincount | addresses      
=====================================
 1 | ABC   |  2          | 3
 2 | DEF   |  1          | 2

表示代码“ABC”用于一个域(example.com)和三个子域; “DEF”用于一个域和两个子域

domaincount显示代码使用的域数,而地址显示使用代码的给定域的地址数。我不确定这是否可以通过单一陈述

1 个答案:

答案 0 :(得分:1)

您可以使用count(distinct)

执行此操作
select c.code, count(distinct l.domain) as numdomains,
       count(l.address) as numaddress
from codes c left outer join
     code_locations cl
     on c.id = cl.code_id left outer join
     locations l
     on l.id = cl.location_id
group by c.code;

编辑:

也许:

select c.code, count(distinct l.domain) as numdomains,
       count(l.address) as numaddress,
       sum(case when l.address like '%example.com% then 1 else 0 end) as NumAddressExample
from codes c left outer join
     code_locations cl
     on c.id = cl.code_id left outer join
     locations l
     on l.id = cl.location_id
group by c.code;