首页 > 解决方案 > 在其中一个表中组合两个表和两列的 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

有人可以指导我正确的方式吗?

标签: mysqlsqlphpmyadminrelational-database

解决方案


我认为这只是一个joingroup 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;

推荐阅读