发新话题
打印

求一个数据库的算法!

求一个数据库的算法!

现有两个表t1和t2
内容分别如下:
t1:
+------+------+
| id   | num  |
+------+------+
|    1 |   18 |
|    3 |   25 |
|    5 |   90 |
|    6 |   80 |
+------+------+
t2:
+------+------+
| ID   | num  |
+------+------+
|    1 |   32 |
|    4 |   56 |
|    5 |   73 |
|    7 |   62 |
+------+------+
要求按(t1.num+t2.num)降序查询,条件t1.id=t2.ID
我写的sql语句:
select (a.num+b.num) num from t1 a,t2 b where a.id=b.ID order by 1 desc;
查询结果:
+------+
| num  |
+------+
|  163 |
|   50 |
+------+
结果只出现ID为1和5两条记录
而我想要的结果是这样:
+------+------+
| ID   | num  |
+------+------+
|    5 |  163 |
|    6 |   80 |
|    7 |   62 |
|    4 |   56 |
|    1 |   50 |
|    3 |   25 |
+------+------+
请问我该怎样实现?

TOP

求一个数据库的算法!

看了你的贴子
你是不是  要这种  效果?
把T1和T2的num  都提出来  混在一起   然后按照  降序  排列
是不是???

TOP

求一个数据库的算法!

嗯,还差一步,混合后把ID值相同的记录求和

TOP

求一个数据库的算法!

自己想的,不知道对不对,对多表查询我也不会..... select * from (select id,(t1.num+t2.num) num from t1,t2 where t1.id=t2.id) t3, (select id,num from t1,t2 where t1.id<>t2.id) t4 order by 1 desc

TOP

求一个数据库的算法!

select id,num from t1,t2 where t1.id<>t2.id 这句好象不行吧? num只能是t1或t2的列属性,不能将其两者合并, 不过我用另外一种方式解决这个问题了:union 谢了

TOP

求一个数据库的算法!

sql有个表的外连接的,不过具体没用过…………

TOP

求一个数据库的算法!

基本上是这样
select id,sum(num) as num from
(
select .. from t1
union all
select .. from t2
) a group by id order by num desc

TOP

发新话题