SQL SELECT或CROSS JOIN逐行加入多个帐户和SUM值

时间:2016-05-27 13:08:35

标签: mysql sql

我有3张桌子

Table1APPLES
Table2ORANGES
Table3BANANAS
每个表中的

都是具有价格和数量的水果

    TABLE1APPLES:

    *Fruit*     *Price*    *Quantity*
----------------------------------------
     GreenApple   $5          8
     RedApple     $3          7


    TABLE2ORANGES:

    *Fruit*     *Price*    *Quantity*
----------------------------------------
     Oranges      $3          8    

    TABLE3BANANAS:

    *Fruit*     *Price*    *Quantity*
----------------------------------------
    YellowBanana  $5          9
    GreenBanana   $4          8

我想找到这些水果的每种组合以及总价格和数量。

示例:

 Fruit       Price  Quantity    Fruit   Price   Quantity     Fruit          Price    Quantity    TotalPrice   TotalQuantity
------------------------------------------------------------------------------------------------------------------------

 Green Apple  $5       8         Orange   $3         8        Yellow Banana  $5       9          $13          25
 Green Apple  $5       8         Orange   $3         8        Green Banana   $4       8          $12          24

 Red Apple    $3       7         Orange   $3         8        Yellow Banana  $5       9          $11          24
 Red Apple    $3       7         Orange   $3         8        Green Banana   $4       8          $10          23

2 个答案:

答案 0 :(得分:0)

正如评论中所提到的,你想要的是笛卡儿联盟。在mysql中,实现它的最简单方法是在没有任何连接条件的情况下连接3个表:

select *
from Table1APPLES
join Table2ORANGES
join Table3BANANAS

答案 1 :(得分:0)

我能够玩弄它而得到了它。

    SELECT *,
    TABLE1APPLES.PRICE + Table2ORANGES.Price + Table3BANANAS.Price AS TotalAmount,
    Table1APPLES.Quantity + Table2ORANGES.Quantity + Table3BANANAS.Quantity AS Quantity
    FROM TABLE1APPLES, Table2ORANGES, Table3BANANAS