mysql - order by from 2 column from different tables -
i trying pull items sales on pos system.
i have few tables need join , order/group by. hope can explained.
table `items`: +---------+--------+ | item_id | name | +---------+--------+ | 33 | thing1 | | 34 | thing2 | | 54 | thing3 | | 67 | thing4 | +---------+--------+ table `kits`: +-------------+------+ | item_kit_id | name | +-------------+------+ | 1 | kit1 | | 2 | kit2 | +-------------+------+ table `sales`: +---------+-------------+---------+ | sale_id | sale_date | total | +---------+-------------+---------+ | 1 | 2016-06-11 | 100.00 | | 2 | 2016-06-12 | 145.00 | +---------+-------------+---------+ table `sale_items`: +-----+---------+----------+---------+ | id | sale_id | line_num | item_id | +-----+---------+----------+---------+ | 1 | 1 | 1 | 33 | | 2 | 1 | 3 | 54 | | 3 | 2 | 1 | 34 | | 4 | 2 | 2 | 67 | +-----+---------+----------+---------+ table `sale_kit_items`: +-----+---------+----------+-------------+ | id | sale_id | line_num | item_kit_id | +-----+---------+----------+-------------+ | 1 | 1 | 2 | 1 | | 2 | 2 | 3 | 2 | +-----+---------+----------+-------------+
i want results like
results: +---------+----------+---------+-------------+ | sale_id | line_num | item_id | item_kit_id | +---------+----------+---------+-------------+ | 1 | 1 | 33 | null | | 1 | 2 | null | 1 | | 1 | 3 | 54 | null | | 2 | 1 | 54 | null | | 2 | 2 | 67 | null | | 2 | 3 | null | 2 | +---------+----------+---------+-------------+
or better if get:
results: +---------+----------+---------+-------------+--------+ | sale_id | line_num | item_id | item_kit_id | name | +---------+----------+---------+-------------+--------+ | 1 | 1 | 33 | null | thing1 | | 1 | 2 | null | 1 | kit1 | | 1 | 3 | 54 | null | thing2 | | 2 | 1 | 54 | null | thing3 | | 2 | 2 | 67 | null | thing4 | | 2 | 3 | null | 2 | kit2 | +---------+----------+---------+-------------+--------+
took me sometime understand scenario...
edit
perhaps should change left joins items
, sale_kit_items
inner joins (i expect ids found in respective tables).
select s.sale_id, si.line_num, si.item_id, null item_kit_id, i.name sales s left join sale_items si on s.sale_id = si.sale_id left join items on si.item_id = i.item_id union select s.sale_id, ski.line_num, null item_id, ski.item_kit_id, k.name sales s left join sale_kit_items ski on s.sale_id = ski.sale_id left join kits k on ski.item_kit_id = k.item_kit_id order 1, 2 ;
Comments
Post a Comment