mysql - 在其中一个表中组合两个表和两列的 MySQL 查询
问题描述
我正在尝试编写一个 SQL 查询,该查询将两个表和其中一个表中的两列组合在一起。所以,我有两张桌子
桌子:Items
ID Material Shape
1 glass jar
2 plastic bottle
3 cardboard box
4 glass bottle
桌子:Diary
ItemID UserID Quantity
2 1 1
1 1 3
3 1 2
2 1 5
4 1 1
预期输出UserID = 1
(按 排序combined quantity
):
Combined column values Combined quantity
plastic bottle 6
glass jar 3
cardboard box 2
glass bottle 1
有人可以指导我正确的方式吗?
解决方案
我认为这只是一个join
和group by
:
select concat_ws(' ', i.material, i.shape) as combined,
sum(d.quantity) as combined_quantity
from items i left join
diary d
on d.itemId = i.id
group by combined
order by combined_quantity desc;
推荐阅读
- ios - 从 Firebase/Firestore 保存和检索 UIColor
- python - Mongoengine 更改文档结构
- ssis - 集成服务目录和链接服务器
- reactjs - 如何使用 redux 只取回一个值而不管理状态
- pine-script - PineScript 问题,将当前系列转移到过去
- javascript - 如何使用变量(而不是单元格引用的硬编码值)在“脚本实验室”中为 Office Excel 加载项设置范围
- android - Firebase 实时数据库拒绝访问时如何显示错误?
- r - 将多个文件中的数据合并到R中的单个data.frame中的计算最快方法?
- sql-server - SSMS 导出到 CSV 麻烦
- javascript - 解构不适用于快速中间件中的 req.*