从不同表格中的2列开始排序

时间:2017-04-14 17:08:59

标签: mysql sql-order-by

我正试图在POS系统上提取所有待售物品。

我有几张桌子需要加入并订购/分组。我希望我能解释一下。

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     |
+-----+---------+----------+-------------+

我希望结果看起来像

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     |
+---------+----------+---------+-------------+
如果我能得到的话,甚至会更好:

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  |
+---------+----------+---------+-------------+--------+

1 个答案:

答案 0 :(得分:1)

我花了一些时间来了解你的情景...

编辑

也许您应该将itemssale_kit_items的LEFT JOIN更改为INNER JOIN(我希望ID可以在相应的表中找到)。

select s.sale_id, si.line_num, si.item_id, null as item_kit_id, i.name
from sales s 
left join sale_items si on s.sale_id = si.sale_id
left join items i on si.item_id = i.item_id
union all
select s.sale_id, ski.line_num, null as item_id, ski.item_kit_id, k.name
from 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 by 1, 2
;

A live demo can be found here