MySQL如何从三个表中获取值

MySQL如何从三个表中获取值,mysql,Mysql,我有3个表,我想从表credit和deposit group中按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 betw

我有3个表,我想从表credit和deposit group中按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;

你的问题是分组

试试这个

      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

我会用工会。我不知道您的模式,因此这是一个工作请求的推测

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

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

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';

问题是什么,错误是什么,问题是什么?我想要在单个查询中具有相同acno的表deposit中的列rs和表credit中的列rs之和。我说这个请求是一个想法,因为我不知道您的数据模型。但是,您应该根据需要轻松地调整查询。