获取mysql和php中不同用户的总值

时间:2013-04-10 07:49:03

标签: php mysql sql

表1

|-----|---------------|---------------------|
| id  | name          |         pid         |
|-----|---------------|---------------------|
| 1   |  ram          |          2          |
| 2   |  rani         |          1          |
| 3   |   ram         |          3          |
|-------------------------------------------|

表2

|-----|---------------|---------------------|
| pid | name          |         price       |
|-----|---------------|---------------------|
| 1   |  soap         |          2000       |
| 2   |  towel        |          1333       |
| 3   |  bed          |          3000       |
|-------------------------------------------|

我需要如下表所示的结果

|-----|---------------|---------------------|
| id  | name          |         price       |
|-----|---------------|---------------------|
| 1   |  ram          |          4333       |
| 2   |  rani         |          2000       |
|-------------------------------------------|

1 个答案:

答案 0 :(得分:2)

SELECT  MIN(a.ID) ID, a.name, SUM(b.Price) Price
FROM    table1 a
        INNER JOIN table2 b
            ON a.PID = b.PID
GROUP   BY a.Name

输出

╔════╦══════╦═══════╗
║ ID ║ NAME ║ PRICE ║
╠════╬══════╬═══════╣
║  1 ║ ram  ║  4333 ║
║  2 ║ rani ║  2000 ║
╚════╩══════╩═══════╝