sql - 在连接表上存储实体列表
问题描述
背景
本质上,我想存储类似的东西:
{
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
表fav_colors:
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 查询中不重复行来完成对象的加载?
解决方案
您目前正在加入与主键不同的实体。您需要加入外键。如果 John 可以拥有最喜欢的宠物和最喜欢的颜色,那么主表应该有用于 和 的列,这些列是和fav_pet_id
的fav_color_id
外键。您还需要将 fav_colors 中的列名从 更改为。一旦这些更改到位,您的查询应如下所示:fav_pet.id
fav_color.id
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。
推荐阅读
- hybris - 克隆 hybris bean 的最佳方法是什么?
- flutter - 每个 Flutter 项目的不同 PUB_CACHE 目录
- javascript - JavaScript:切片对象名称
- constraints - 任务路线分配中的链接任务(Optaplanner)
- python - 使用 Python 将通用 JSON 解析/保存到 Db
- php - fopen(/vendor/dompdf/dompdf/lib/fonts/glyphicons-halflings-normal_c47afe5539ba1b2094563d54dce2def7.ufm):无法打开流:权限被拒绝
- arrays - 如何为猫鼬中的多个对象分配相同的ID?
- c++ - 如何将 std::find_if 与唯一指针向量一起使用?
- javascript - forEach() 不会更新数据库调用中的值
- huawei-mobile-services - 许多用户告诉我,我的应用程序的(安装)按钮在华为应用程序库中被禁用