A表
pid 中存储的是他的上级的ID,如A表的第4条记录的pid为1,就表示他的上级的id为1,那么也就是说d是a的下级! id | name | pid |
1 a
2 b
3 c
4 d 1
5 e 1
4 f 2
4 g 2B表
表中id为自动增长. id | name | amount | place
1 d 100 AA
2 d 200 AA
3 d 300 BB
4 d 400 BB
5 e 100 AA
6 e 200 AA
7 e 300 AA
8 e 400 BB
9 e 500 CC
10 f 500 AA
11 f 500 BB
12 f 500 CC
13 g 500 AA联合A表和B表查询结果为 A.name | sum(amount) | B.place |
a 900 AA (B表中所有上线为a的name AND place='AA' 的sum(amount))
a 1100 BB (B表中所有上线为a的name AND place='BB' 的sum(amount))
a 500 CC
b 1000 AA
b 500 BB
B 500 CC也就是按照B表中name的上级( B表中name的上级需要查A表得知道) 和B表中的place对B表的amount进行求和.
pid 中存储的是他的上级的ID,如A表的第4条记录的pid为1,就表示他的上级的id为1,那么也就是说d是a的下级! id | name | pid |
1 a
2 b
3 c
4 d 1
5 e 1
4 f 2
4 g 2B表
表中id为自动增长. id | name | amount | place
1 d 100 AA
2 d 200 AA
3 d 300 BB
4 d 400 BB
5 e 100 AA
6 e 200 AA
7 e 300 AA
8 e 400 BB
9 e 500 CC
10 f 500 AA
11 f 500 BB
12 f 500 CC
13 g 500 AA联合A表和B表查询结果为 A.name | sum(amount) | B.place |
a 900 AA (B表中所有上线为a的name AND place='AA' 的sum(amount))
a 1100 BB (B表中所有上线为a的name AND place='BB' 的sum(amount))
a 500 CC
b 1000 AA
b 500 BB
B 500 CC也就是按照B表中name的上级( B表中name的上级需要查A表得知道) 和B表中的place对B表的amount进行求和.
解决方案 »
- MYSQL NOT IN优化问题
- mysql 触发器 为什么不能支持中文字段呢?
- 3-4位字符串,用char(4)好还是var(4)呢?
- SQL查詢問題
- mysql远程连接不上,新问题,查了一天了。不吃饭在线等!!
- 请问MYSQL 中 等效 mssql中 REPLICATE 的函数是什么?
- 帮忙看看我这个存储过程为什么老报错!
- mysql5.0的中文问题求助!!!
- postgresql 和 mysql是否可同时安装,会不会有什么影响?
- show full processlist Sleeping的连接数据可以删除吗
- 求MFC通过ODBC连接MYSQL例子
- 存储过程中怎样把结果集查询出来,并把值CONCAT成字符串输出
select t1.name,t2.samount,t2.place
from A t1,
(select pid,sum(amount) samount,place
from A,B where A.name=B.name
group by pid,place) t2
where t1.id=t2.pid;
+------+------+------+
| id | name | pid |
+------+------+------+
| 1 | a | NULL |
| 2 | b | NULL |
| 3 | c | NULL |
| 4 | d | 1 |
| 5 | e | 1 |
| 4 | f | 2 |
| 4 | g | 2 |
+------+------+------+
7 rows in set (0.00 sec)mysql> select * from test2;
+------+------+--------+-------+
| id | name | amount | place |
+------+------+--------+-------+
| 1 | d | 100 | AA |
| 2 | d | 200 | AA |
| 3 | d | 300 | BB |
| 4 | d | 400 | BB |
| 5 | e | 100 | AA |
| 6 | e | 200 | AA |
| 7 | e | 300 | AA |
| 8 | e | 400 | BB |
| 9 | e | 500 | CC |
| 10 | f | 500 | AA |
| 11 | f | 500 | BB |
| 12 | f | 500 | CC |
| 13 | g | 500 | AA |
+------+------+--------+-------+
13 rows in set (0.00 sec)mysql> select t1.name,t2.samount,t2.place
-> from test1 t1,
-> (select pid,sum(amount) samount,place
-> from test1,test2 where test1.name=test2.name
-> group by pid,place) t2
-> where t1.id=t2.pid;
+------+---------+-------+
| name | samount | place |
+------+---------+-------+
| a | 900 | AA |
| a | 1100 | BB |
| a | 500 | CC |
| b | 1000 | AA |
| b | 500 | BB |
| b | 500 | CC |
+------+---------+-------+
6 rows in set (0.00 sec)
from a t1 inner join
(
select pid,sum(amount) as amount,place
from a inner join b using(name)
group by pid,place
) t2 on t1.id=t2.pid;