2017-03-12 28 views
0

这些都是我的表:SQL组加入

create table articles(
    id integer auto_increment, 
    site varchar(64) not null, 
    title varchar(512) not null, 
    link varchar(512) not null, 
    pub_date datetime not null, 
    primary key(id) 
); 

create table entities (
    id integer auto_increment, 
    entity varchar(1024) not null, 
    entity_type varchar(32) not null, 
    primary key(id) 
); 

create table articles_entities (
    article_id integer not null, 
    entity_id integer not null, 
    foreign key(entity_id) references entities(id), 
    foreign key(article_id) references articles(id) 
); 

这是什么,我试图做的出发点:

select count(*), entity_type from entities group by entity_type; 

我明明得到的东西看起来是这样的:

+----------+---------------+ 
| count(*) | entity_type | 
+----------+---------------+ 
| 15418 | locations  | 
| 21789 | misc   | 
| 62306 | organizations | 
| 121307 | people  | 
+----------+---------------+ 

我想是这样的:

+----------+---------------+------+ 
| count(*) | entity_type | site | 
+----------+---------------+------+ 
| 15418 | locations  | ABC | 
| 21789 | misc   | ABC | 
| 62306 | organizations | ABC | 
| 121307 | people  | ABC | 
| 13418 | locations  | CNN | 
| 22789 | misc   | CNN | 
| 65306 | organizations | CNN | 
| 132307 | people  | CNN | 
+----------+---------------+------+ 

如何设置该查询来提供这种计数?

+0

提示:'JOIN'。然后再次“加入”。 –

+0

...你的问题是什么?你是否试图将三张桌子一起加入? – Bakuriu

回答

1

你需要一个join

select count(*), entity_type, site 
from entities 
left join articles_entities on entity_id = entities.id 
left join articles on article_id = articles.id 
group by entity_type, site; 

我用left join,前提是,你可能不符合要包含在结果文章实体。如果情况并非如此,那么您可以删除left