连接多个表并生成多个记录

时间:2013-03-31 20:27:52

标签: mysql

我有3个信息表。

表1:订单

+---------+----------------+------------+---------------+
| OrderID | OrderDate      | Community   | Status       |
+-------------------------------------------------------+
 1        | 1 march 2013   | S1          | Approved
 2        | 5 march 2013   | S2          | Aporoved
 3        | 7 march 2013   | Z1          | Approved
+-------------------------------------------------------+

表2:OrderArtickles

+------------------------------------------------------------------+
|Ordertitem  | OrderID     | ArtikelID   | UnitPrice    | Delivered |
+------------------------------------------------------------------+
| 1          | 1           | 20          | 5            | yes
| 2          | 1           | 20          | 5            | yes
| 3          | 2           | 21          | 10           | yes
| 4          | 3           | 30          | 50           | yes
+-------------------------------------------------------------------+

表3:用户

+-----------------------------------------------------+
| Userid     | Username   | Community     | Department |
+-----------------------------------------------------+
| 1          | User1      | S1            | S
| 2          | User2      | S2            | S
| 3          | User3      | Z1            | Z
+-----------------------------------------------------+

我需要一个提供以下输出的MySQL查询:

+--------------------------------------+
| Department     | TotalPriceOfArtikels 
+--------------------------------------+
| S              | 20                   
| Z              | 50                   
+--------------------------------------+

我尝试使用JOIN,SUM,GROUP BY但没有结果。我遇到的问题是一个订单给出了多篇文章。谁能帮帮我?

2 个答案:

答案 0 :(得分:1)

试试这个

    select Department  , sum(UnitPrice) as TotalPriceOfArtikels 
    from users u
    inner join Orders o
    on o.Community = u.Community
    inner join OrderArtickles oa
    on oa.OrderId = o.OrderId
    group by Department

DEMO HERE

输出:

    Department  TotalPriceOfArtikels
        S             20
        Z             50

答案 1 :(得分:0)

这样的事情:

select us.Department,
sum ( art.UnitPrice ) as TotalPriceOfArtikels
from user us
 left join orders ors
on ( us.Community = ors.Community)
 left join OrderArtickles art
on ( ors.OrderID = art.OrderID)
group by us.Department

------------------ EDITED ------------------------

我在mysql中复制了表的相同值和结构,结果很好,它给了我:

Department  TotalPriceOfArtikels
    S             20
    Z             50

也许你想检查一个条件,比如delivery = yes或status = aprobed ?? ....使用此查询结果它与你发布的相同;)

Saludos;)