mysql - SQL 按两个以上联接进行分组

标签 mysql 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  |
+----------+---------------+------+

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

最佳答案

您需要加入:

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

关于mysql - SQL 按两个以上联接进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42750526/

相关文章:

mysql - 如何在 UPDATE 语句中使用 JOIN?

mysql - Django 无法连接到 MySQL

sql - 从存储为文本的数据库中选择财务值

mysql - 如何选择多个喜欢和其他条件的mysql

Mysql 工作台 : Default varchar value as empty

mysql - sql 在更新时创建触发器

Mysql 一次查询优化

sql - 如何在 SQL 更新中划分列值?

以子查询作为数据源的 SQL 更新不起作用 (Postgresql)

c# - Entity Framework 的子查询