从不同的表中选择两个不同的数据并显示该值

时间:2013-08-27 14:26:04

标签: mysql sql

我有两个表tbl_product和tbl_sales。我的问题是,如何从两个不同的表中获取数据并水平显示,并将tbl_rsales的“总计”和“折扣”相加。例如

    the ff data in my tbl_products are

    id|pcode|pdesc    |
    1 |1000 |wire     |
    2 |1443 |capactor |

    and the ff data in my tbl_sales are

    id|total|discount| pcode |
    1 |1000 |10      | 1000  |
    2 |2000 |20      | 1443  |
    3 |1000 |10      | 1000  |
    4 |1000 |20      | 1443  |

预期输出必须是这样的。我如何从两个不同的桌子中选择它?

    id | pcode | pdesc     | total | discount |
    1  | 1000  | wire      | 2000  | 20       |
    2  | 1443  | capacitor | 3000  | 40       |

6 个答案:

答案 0 :(得分:0)

试试这个:

SELECT P.id, P.pcode, P.pdesc, COALESCE(SUM(S.total),0), COALESCE(SUM(s.discount),0)
FROM tbl_products P
LEFT OUTER JOIN tbl_sales S
ON P.pcode = S.pcode
GROUP BY P.id, P.pcode, P.pdesc

答案 1 :(得分:0)

此?

SELECT 
    tbl_products.*, 
    SUM(tbl_sales.total) as total, 
    SUM(tbl_sales.discount) as discount
FROM tbl_products 
LEFT JOIN tbl_sales ON tbl_sales.pcode = tbl_products.pcode
GROUP BY pcode
ORDER BY total ASC

答案 2 :(得分:0)

使用这样的连接:

SELECT * FROM tbl_products INNER JOIN tbl_sales ON tbl_sales.pcode = tbl_products.pcode ORDER BY tbl_products.pcode

将使它成为一个表。

答案 3 :(得分:0)

这可以通过简单的JOINGROUP BY

来完成
SELECT
    p.id,
    p.pcode,
    p.pdesc,
    SUM(s.total) AS total,
    SUM(t.discount) AS discount
FROM 
    tbl_products AS p
LEFT JOIN 
    tbl_sales AS s ON
        s.pcode = p.pcode
GROUP BY
    p.pcode
ORDER BY
    /* your call */

答案 4 :(得分:0)

select p.id,p.pcode,p.desc,sum(s.sales),sum(s.discount)
from tbl_products p, tbl_sales s
where p.id = s.id
group by p.id,p.pcode,p.desc;

答案 5 :(得分:0)

试试这个:

SELECT 
    tbl_products.*, 
    SUM(tbl_sales.total) as total, 
    SUM(tbl_sales.discount) as discount
FROM tbl_products,tbl_sales 
where tbl_sales.pcode = tbl_products.pcode
GROUP BY pcode
ORDER BY total ASC