MySQL如何从三个表中获取值

时间:2014-03-23 07:52:23

标签: mysql

我有3张桌子,我想通过acno从表信用和存款组中选择rs的总和。以下是我的询问:

select a.amname,sum(d.rs),sum(c.rs),a.acno 
from deposit d,account a,credit c 
where
a.acno=d.acno && a.acno=c.acno 
&& d.date1 between '$date1' and '$date2'
&& c.date1 between '$date1' and '$date2' 
&& a.scode='3' 
group by d.acno,c.acno;

3 个答案:

答案 0 :(得分:1)

你的问题在于GROUP BY。

试试这个

      select a.amname,sum(d.rs),sum(c.rs),a.acno 
      from deposit d
      INNER JOIN account a ON a.acno=d.acno 
      INNER JOIN credit c  ON a.acno=c.acno
      where  d.date1 between '$date1' and '$date2'
      and c.date1 between '$date1' and '$date2' 
      and  a.scode='3' 
      group by a.amname,c.acno

答案 1 :(得分:1)

您需要分别将信用卡和存款表“分组”,然后将结果包括在一起。它可能看起来像这样:

select a.acno, a.amname, c.sumRS, d.sumRS 
from account a
INNER JOIN  (select acno, SUM(rs) as sumRS from credit where date1 between '$date1' and '$date2' group by acno) c ON a.acno=c.acno 
INNER JOIN (select acno, SUM(rs) as sumRS from deposit where date1 between '$date1' and '$date2' group by acno) d ON a.acno=d.acno
where a.scode='3';

答案 2 :(得分:0)

我会使用工会。我不知道你的架构,所以它是对工作请求的推测

select sum(rs), acno from
(
    select sum(rs),acno 
    from deposit
    where date1 between '$date1' and '$date2'
    and scode='3' 
    group by acno
  union
    select sum(rs),acno 
    from account
    where date1 between '$date1' and '$date2' 
    group by acno
  union
    select sum(rs),acno 
    from credit
    where date1 between '$date1' and '$date2'
    group by acno
)
group by acno