返回添加具有3个表中唯一记录的公共记录

时间:2014-12-26 05:57:45

标签: mysql

我有3个表table1table2table3,它们之间没有任何关系。

的MySQL> select * from table1;

+-----------+--------+---------+
| scname    | sccode | samount |
+-----------+--------+---------+
| CustomerA | C1     |   20000 |
| CustomerB | C2     |   10000 |
+-----------+--------+---------+

sccode是客户主表的外键。

的MySQL> select * from table2;

+--------------+---------+---------------+----------+--------+---------+
| raccname     | ramount | raccname2     | ramount2 | raccid | racc2id |
+--------------+---------+---------------+----------+---------+--------+
| CustomerA    |   10000 | Secured Loans |    10000 | C1     | 5       |
| CustomerB    |   12000 | SupplierB     |    12000 | C2     | S2      |
| Fixed Assets |    1000 | SupplierB     |     1200 | 4      | S2      |
+--------------+---------+---------------+----------+--------+---------+

raccidracc2id分别是raccnameraccname2的代码,但它们与某些表没有关系

的MySQL> select * from table3;

+--------------+----------+---------------+-----------+--------+----------+
| pyaccname    | pyamount | pyaccname2    | pyamount2 |pyaccid | pyacc2id |
+--------------+----------+---------------+-----------+--------+----------+
| SupplierA    |    13000 | Secured Loans |     15000 | S1     | 5        |
| Fixed Assets |    12000 | SupplierB     |     12000 | 4      | S2       |
+--------------+----------+---------------+-----------+--------+----------+

pyaccidpyacc2id分别是pyaccnamepyaccname2的代码,但它们与某些表没有关系。

我需要像

这样的输出
+--------------+---------+
| account      |  amount | 
+--------------+---------+
| CustomerA    |   30000 | 
| CustomerB    |   22000 | 
| Fixed Assets |   13000 | 
| Secured Loans|   25000 | 
| SupplierA    |   13000 |
| SupplierB    |   25200 | 
+--------------+---------+

意味着添加常见记录和唯一记录。

2 个答案:

答案 0 :(得分:0)

尝试此查询:

 SELECT name, sum(amount) FROM (
    (SELECT scname AS name, samount AS amount FROM table1)
    UNION ALL
    (SELECT raccname AS name, ramount AS amount FROM table2)
    UNION ALL
    (SELECT raccname2 AS name, ramount2 AS amount FROM table2)
    UNION ALL
    (SELECT pyaccname AS name, pyamount AS amount FROM table3)
    UNION ALL
    (SELECT pyaccname2 AS name, pyamount2 AS amount FROM table3)
) p GROUP BY name;

答案 1 :(得分:0)

UNION运算符仅返回在任一结果中出现的不同行,而UNION ALL运算符返回所有行。 UNION ALL运算符不会消除重复的选定行。

所以这会做点什么:

SELECT T1.`scname` "Account", sum(T1.`scamount`) "amount"
   FROM table1 T1
UNION
SELECT T2.`raccname` "Account", sum(T2.`ramount`) "amount"
   FROM table2 T2
UNION
SELECT T3.`pyaccname` "Account", sum(T3.`pyamount`) "amount"
   FROM table3 T3
GROUP BY `scamount`,`ramount`,`pyamount`;