我有两张表,第一张表:表名:table1,字段(id,user_id,username,money)。第二张表:表名:table2,字段 (id,user_id,money),
现在是部门A往table1里插,部门B往table2里插,现在要做两张表的汇总:两张表money字段加起来超过10000的提取出来
select a.username,a.money as x,b.money as y from table1 as a,table2 as b where a.user_id=b.user_id  group by a.user_id having x+y>=10000 order by null。
现在是这条sql:情况1,如果两张表中都有同样的user_id并且加起来超过10000,有结果。
                      例:table1(1,2001001,张三,5000),table2(3,2001001,张三,6000)
               情况2,只有一张表中有一个user_id。无结果                                     
                      例:table1(1,2001001,张三,12000),table2中没有user_id=2001001的记录。
                              但是情况2是满足条件的。小弟表述可能不清楚,但这个问题很棘手,各位有什么好的解决方法,请告之。谢了

解决方案 »

  1.   

    ... IFNULL(x,0)+IFNULL(y,0)> =10000  ...
      

  2.   

    在LZ的基础上加个条件不就可以了吗,限定表二的userid<>'' ,这样不就解决了你情况二的问题吗。不过这样与好像不是很合理。
      

  3.   

    看你的库结构似乎不会出现table1没有,table2有的情况? (因为你的username仅在table1表)
    如果这样就很简单,用left join
    另外看你用了group by? 是否你的table2中有同一个user的很多条记录?需要总计?
    那么在table1中是否也会有同一user的多条??? 
    希望能先说明这些情况,下面这个可以先试一下,
    select  a.username,
            a.money   as   x,
            sum(b.money)   as   y   
    from   table1   as   a 
             left join table2   as   b   
           on a.user_id=b.user_id
    where 1
    group   by   a.user_id   
    having  ( x+ sum(b.money) > =10000  or x>10000 )
    order   by   null其它情况也可以通过left join和union得出,
    如果你上面的不行,我再写给你
      

  4.   

    select   a.username,a.money   as   x,b.money   as   y   from   table1   as   a full join table2   as   b   on a.user_id=b.user_id     group   by   a.user_id   having   x+y> =10000   order   by   null
      

  5.   

    其实table1和table2就是两个视图,是我在原始表的基础上做的视图,在原始表中会有多条user_id一样的记录,但是在现在的table1和table2中已经把具有同一个user_id的money字段进行了累加,所以在我table1和table2中不会出现重复的user_id。现在我是用了一个left join和union写的
    $sql="select a.user_id,a.username,a.money as fee1,b.money as fee2 from table1 as a left join table2 as b on a.user_id=b.user_id having fee1>=10000 or fee1+fee2>=10000 union select user_id,username,money,'xxx' from table2 where money>=10000 and user_id not in (select user_id from table1)";此sql效率很低
      

  6.   

    我用的是mysql,full join好像不支持