MySQL - 如何从这三个表中加入和获取数据?

时间:2017-11-20 19:44:48

标签: mysql

我有以下三个表:

商店表

+----------+------------+
| STORE_ID | STORE_NAME |
+----------+------------+
|        1 | Shop 1     |
|        2 | Shop 2     |
|        3 | Shop 3     |
+----------+------------+

员工表

+--------+------------+----------+---------+
| EMP_NO | MANAGER_NO | EMP_NAME | STORE_ID |
+--------+------------+----------+---------+
|   3465 |       4356 | A Smith  |       1 |
|   4356 |            | M Jones  |       2 |
|   7645 |       4356 | J Adam   |       3 |
+--------+------------+----------+---------+

付款表

+------------+------------+-------+--------+----------+
| PAYMENT_ID |    DATE    | TOTAL | EMP_NO | STORE_ID |
+------------+------------+-------+--------+----------+
|          1 | 01/01/2016 | 20.00 |   7645 |        3 |
|          2 | 10/02/2016 | 10.00 |   3465 |        1 |
|          3 | 15/03/2016 | 5.00  |   3465 |        1 |
|          4 | 25/04/2016 | 50.00 |   7645 |        3 |
|          5 | 30/05/2016 | 35.00 |   7645 |        3 |
+------------+------------+-------+--------+----------+

根据上面的表格,我如何创建显示3个商店中每个商店的销售数据的视图表。

每个表都需要显示以下内容:

  • 商店名称,商店经理名称,该商店的顶级销售人员名称以及该人的销售数量。

我目前已完成以下操作,但完全卡住了。我对SQL很新,过去曾使用过join,但似乎无法解决这个问题。

SELECT  s.store_id AS "Store Name",
    e1.manager_no AS "Manager Name",    
    e2.emp_name AS "Salesperson",   
    SUM(p.total) AS "Sales Value"
FROM store_table s
JOIN

1 个答案:

答案 0 :(得分:2)

你可以根据你的情况修改这个例子,但我认为它可能是这样的:

  SELECT  s.store_id AS "Store Name",
        e.manager_no AS "Manager Name",    
        e.emp_name AS "Salesperson",   
        SUM(p.total) AS "Sales Value"
    FROM store_table s
    INNER JOIN employee_table AS e
        ON s.STORE_ID = e.STORE_ID 
    INNER JOIN payment_table AS p
        ON s.STORE_ID = p.STORE_ID