结合两个表和其中一个表中的两列的MySQL查询

时间:2019-04-10 13:52:35

标签: mysql sql phpmyadmin relational-database

我正在尝试编写一个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

有人可以指引我正确的方向吗?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

查询

select Material+SPACE(1)+ SHAPE [Combined column values ], 
SUM(QUANTITY) [Combined quantity]
from Items 
left join diary on Items.itemiD = diary.itemID  
GROUP BY ITEMS.itemiD, Material, SHAPE 

输出

enter image description here