两个表,不同的值

时间:2014-05-02 11:24:47

标签: php mysql sql phpmyadmin

tbl_expenses
sitename 
amount


tbl_payment
sitename 
amount

如何从这两个表中获得不同的网站名称和数量作为SUM?

6 个答案:

答案 0 :(得分:0)

如果您只想要不同的值,请使用以下查询 -

select distinct sitename,amount from tbl_expenses
UNION 
select distinct sitename,amount from tbl_payment

答案 1 :(得分:0)

试试这个。

select 
distinct(sitename) 
from tbl_expenses 
inner join tbl_payment 
on tbl_expenses.sitename=tbl_payment.sitename;

答案 2 :(得分:0)

 select sitename,SUM(amount) from tbl_expenses 
 inner join tbl_payment
 on tbl_expenses.sitename=tbl_payment.sitename
 group by sitename

答案 3 :(得分:0)

以下是使用union all和聚合的一种方法:

select sitename, sum(expense) as expense, sum(payment) as payment
from ((select sitename, amount as expense, 0 as payment
       from tbl_expenses
      ) union all
      (select sitename, 0 as expense, amount as payment
       from tbl_payment
      )
     ) ep
group by sitename;

你的问题比你想象的更微妙。您希望确保所有站点都包含在输出中,即使该站点仅出现在一个表中。您还必须小心笛卡尔积,这就是join不是正确解决方案的原因。

答案 4 :(得分:0)

试试这个:

SELECT sitename, SUM(amount) sum_amount FROM
(
  SELECT sitename,amount FROM tbl_expenses
  UNION ALL
  SELECT sitename,amount FROM tbl_payment
) A
GROUP BY sitename

答案 5 :(得分:0)

select sitename, sum(amount) from (
  select sitename, amount from tbl_expenses
  union
  select sitename, amount from tbl_payment
) test group by sitename