用户
 找回密码
 入住 CI 中国社区
搜索
查看: 2604|回复: 4
收起左侧

急!请教一个mysql 查询问题

[复制链接]
发表于 2011-2-17 16:54:26 | 显示全部楼层 |阅读模式
本帖最后由 deader 于 2011-2-17 17:11 编辑

数据表如下:
表income
id   money  ct_id(客户id)
1   100.00   30
2   200.00   30
3   600.00   31

表invoice
i_id i_ct_id(客户id) i_money
1      30                    200
2      32                    600

表receivables
r_id r_ct_id(客户id) r_money
1      30                     500
2      32                     400


/*-------------------
补充一个客户表 clients
ct_id     ct_name(客户名称)
30          客户1
31          客户2
32          客户3
-------------------------*/

想要得到每个客户id相关的三个表各个字段的数据和
期望的结果如下:

client_id    sum_money    sum_i_money    sum_r_money
30               300                  200                     500
31               600                  null                      null
32                null                   600                    400   


请教sql应该如何写?
搞了好久了,没弄出来,求大侠帮忙,感激万分!
发表于 2011-2-17 17:55:17 | 显示全部楼层
非得一个sql查出来么?
那就得子查询,最直观的方法就是
select (select sum(income.money) from income where ct_id=c.client_id) as sum_money,(参考第一个) as sum_i_money,(参考第一个) as sum_r_money from clients c

这样应该可以实现
 楼主| 发表于 2011-2-18 09:19:42 | 显示全部楼层
嗯,感谢版主,可以实现。
再请教一下,如果要按照查询结果“sum_money”排序,应该怎么写?

直接在 “...... from clients c”后添加 ORDER BY sum_money 没有效果。
 楼主| 发表于 2011-2-18 09:39:10 | 显示全部楼层
找到办法了,再嵌套一层,就可以实现排序,不知道有没有更好的办法?
我用的这个:
SELECT * FROM
       (select (select sum(income.money) from income where ct_id=c.client_id) as sum_money,(参考第一个) as sum_i_money,(参考第一个) as sum_r_money from clients c)
        AS a
        ORDER BY sum_money DESC;
发表于 2011-2-18 10:16:30 | 显示全部楼层
同求好的办法

本版积分规则