使用2个表获取不同名称的总值

时间:2013-04-10 09:42:32

标签: php mysql

我通过比较2个表来得到2个表,我们需要结果。 结果表在最后一个表中给出。 表a

|-----|---------------|---------------------|
| id  | name          |         pid         |
|-----|---------------|---------------------|
| 1   |  ram          |         EW2         |
| 2   |  rani         |         EW1         |
| 3   |  ram          |         EW3         |
| 4   |  rani         |         EW4         |
| 6   |  ram          |         EW5         |
|-------------------------------------------|

表b

|-----|---------------|-------|--------------|
| id  | name          |  pid  |  price       |
|-----|---------------|-------|--------------|
| 1   |  soap         |  EW1  |   2000       |
| 2   |  towel        |  EW2  |   1333       |
| 3   |  bed          |  EW3  |   3000       |
| 4   |  facewash     |  EW4  |    250       |
| 5   |  T.soap       |  EW5  |    300       |
|--------------------------------------------|

我需要使用php mysql

给出如下表所示的结果
|-----------------|-----------|---------------------|
| no of products  | name      |  total_ price       |
|-----------------|-----------|---------------------|
|       3         |  ram      |          4833       |
|       2         |  rani     |          2250       |
|---------------------------------------------------|

3 个答案:

答案 0 :(得分:1)

SELECT COUNT(b.id), a.name, SUM(b.price)
FROM a LEFT JOIN b ON a.pid=b.pid
GROUP BY a.name

答案 1 :(得分:0)

$query = " SELECT count(tableA.name) ,tableA.name,sum(tableB.price)
           FROM tableA
           INNER JOIN tableB 
              ON tableA.pid=tableB.pid
           GROUP BY tableA.name "

答案 2 :(得分:0)

SELECT COUNT(a.id)AS NO_OF_PRODUCTS,a.name AS NAME,SUM(b.price)AS TOTAL_PRICE 来自LEFT JOIN b ON b.pid = a.pid GROUP BY a.name