Mysql连接三个表的数据(多对多关系)

标签 mysql sql many-to-many relationship

这是我的 mysql 数据库架构:

db schema 我想创建查询,以以下方式返回有关所有训练的数据:

training.*, [type.type], [voivodeship.name] 如果没有与给定训练相关的类型或省份,则应在列值中返回 null。

例如:

 {
    "id": 1,
    "name": "Example training 2",
    "description": "This is a description 2",
    "status": "status 2",
    "registerFrom": null,
    "registerTo": null,
    "DateOfInsert": "2018-02-06T12:00:57.000Z",
    "training types": "Example type 1,Example type 3,Example type 2"
    "localizations": "loc 1, loc 3"
 },
...
 {
    "id": 99,
    "name": "Example training 99",
    "description": "This is a description 99",
    "status": "status 2",
    "registerFrom": null,
    "registerTo": null,
    "DateOfInsert": "2018-02-06T12:00:57.000Z",
    "training types": null,
    "localizations": null
 },
 {
    "id": 99,
    "name": "Example training 99",
    "description": "This is a description 99",
    "status": "status 2",
    "registerFrom": null,
    "registerTo": null,
    "DateOfInsert": "2018-02-06T12:00:57.000Z",
    "training types": "Example type 9,Example type 4,Example type 2",
    "localizations": "loc 56, loc 32"
  },

这是我当前的查询,它返回带有有关其本地化信息的培训(遗憾的是,它不会返回没有本地化信息的培训),而且我也不知道如何修改它以返回所有类型:

SELECT `training`.*, GROUP_CONCAT(`voivodeship`.`name`) AS `Localizations`
FROM `training_localization` 
INNER JOIN `training` ON (`training_localization`.`training_id` = `training`.`id`) 
INNER JOIN `voivodeship` ON (`training_localization`.`voivodeship_id` = `voivodeship`.`id`) 
GROUP BY `training`.`id`

我对sql不太有经验。是否可以通过一个查询来实现?

根据戈登的回答,我提出了新的查询,看起来它正在工作:):

SELECT t.*, GROUP_CONCAT(vs.name) AS Localizations,  tw.types AS types
FROM training t 
     LEFT JOIN training_localization tl ON tl.training_id = t.id 
     LEFT JOIN voivodeship vs ON tl.voivodeship_id = vs.id
     LEFT JOIN(
        SELECT t.*, GROUP_CONCAT(ty.type) AS Types
        FROM training t 
             LEFT JOIN training_type tt ON tt.training_id = t.id 
             LEFT JOIN type ty ON tt.type_id = ty.id
        GROUP BY t.id
        ) tw ON tw.id = t.id
GROUP BY t.id;

最佳答案

如果您想要全部内容,请考虑“外部连接”。如果您想要所有训练,那应该是一系列左连接中的第一个表:

SELECT t.*, GROUP_CONCAT(vs.name) AS Localizations
FROM training t LEFT JOIN
     training_localization tl
     ON tl.training_id = t.id LEFT JOIN 
     voivodeship vs
     ON tl.voivodeship_id = vs.id
GROUP BY t.id;

注释:

  • LEFT JOIN 保留第一个表中的所有内容以及后续表中的匹配行(除非您使用内部联接或 where 子句撤消它)。
  • 表别名使查询更易于编写和阅读。
  • 消除不必要的反引号使查询更易于编写和阅读。

关于Mysql连接三个表的数据(多对多关系),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48649670/

相关文章:

MySQL - Pythonanywhere - 同时添加 2 个值

sql - SQL Server 表索引问题

sql - 为什么没有选项使用 ssms 将数据导入到 Azure 数据库?

Laravel 获取同类产品

具有外键和与同一模型的多对多关系的 Django 模型

php - 尝试在 MySQL 数据库表中存储/保存分数

PHP导出DBF文件格式

mysql - 当我使用Ruby添加记录时,数据库中的主键是32字节空白

sql - 如何在 SQL Server 2000 中生成一个填充有日期的临时表?

c# - 如何使 ef core 中的逆属性不返回 null 而返回空列表