【问题标题】:Storing list of entity over joined tables在连接表上存储实体列表
【发布时间】:2018-05-07 15:47:07
【问题描述】:

背景

本质上,我想存储如下内容:

{
  id : 1, 
  name : 'john', 
  favorite_pets : ['cat', 'dog'], 
  favorite_colors : ['red', 'white', 'green']
}

在具有三个表的关系数据库中:

主表:

id name
1  John

表fav_pets:

id pet
1  cat
1  dog

表格最喜欢的颜色:

id pet
1  red
1  white
1  green

问题

我想要一个返回这个的 SQL 查询:

id  name  pet  color
1   john  cat  red
1   john  dog  white
1   john  null green

问题是如果我这样做:

select * from main 
outer join fav_pets on main.id=pet.id 
outer join fav_colors on main.id=fav_colors.id;

它将返回一个包含 6 行的结果集:

id  name  pet  color
1   john  cat  red
1   john  cat  white
1   john  cat  green
1   john  dog  red
1   john  dog  white
1   john  dog  green

我能否在一个 SQL 查询中不重复行来完成对象的加载?

【问题讨论】:

  • 您(打算)使用哪个 DBMS?

标签: sql arrays object relational-database


【解决方案1】:

您目前正在加入与主键不同的实体。您需要加入外键。如果 John 可以拥有最喜欢的宠物和最喜欢的颜色,那么主表应该有 fav_pet_idfav_color_id 的列,它们的外键是 fav_pet.idfav_color.id。您还需要将 fav_colors 中的列名从 pet 更改为 color。完成这些更改后,您的查询应如下所示:

select main.name, fav_pets.pet, fav_colors.color 
from main 
left outer join fav_pets on main.pet_id=pet.id 
left outer join fav_colors on main.color_id=fav_colors.id;

阅读表规范化、主键和外键。从这个链接开始https://www.w3schools.com/sql/sql_create_db.asp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    相关资源
    最近更新 更多