问题描述
我有多个表试图在MySql中使用UNION ALL和LEFT JOIN从所有表中获取值,我使用的查询看起来像下面这样。
(SELECT
t1.name,t2.cat,t3.utt,t4.gcost,t4.net
FROM table_one as t1
LEFT JOIN table_three as t2
ON t2.id = t1.ct
LEFT JOIN table_four as t3
ON t3.id = t1.ut
LEFT JOIN table_five as t4
ON t4.gid = t1.id
) UNION ALL
(SELECT
t1.name,t4.net
FROM table_tow as t1
LEFT JOIN table_three as t2
ON t2.id = t1.ct
LEFT JOIN table_four as t3
ON t3.id = t1.ut
LEFT JOIN table_five as t4
ON t4.gid = t1.id
)
但上述查询在MySQL中返回双精度值
这是小提琴链接:http://sqlfiddle.com/#!9/bd30ba/1
任何帮助将不胜感激。
谢谢
更新
根据P.Salmon问题了解上述查询用于固定资产应用的完整逻辑,因此固定资产具有多个项目值,例如:
- 实际价格。
- 累计折旧
- 当前值
- ...
因此,查询中的查询有2个不同的价格/金额,查询应为每个参考行ID返回两个值。
解决方法
谢谢大家的帮助,但这些都没有帮助我,我知道table_five中有重复的ID,来自table_one和table_tow ...解决问题的唯一方法是在table_one,table_tow中添加新的序列ID ... AS
seq_.time();
在插入过程中在table_five中添加相同的顺序..之后,我将查询更改为。
(SELECT
t1.name,t2.cat,t3.utt,t4.gcost,t4.net
FROM table_one as t1
LEFT JOIN table_three as t2
ON t2.id = t1.ct
LEFT JOIN table_four as t3
ON t3.id = t1.ut
LEFT JOIN table_five as t4
ON t4.gid = t1.id
AND t4.seq = t1.seq
) UNION ALL
(SELECT
t1.name,t4.net
FROM table_tow as t1
LEFT JOIN table_three as t2
ON t2.id = t1.ct
LEFT JOIN table_four as t3
ON t3.id = t1.ut
LEFT JOIN table_five as t4
ON t4.gid = t1.id
AND t4.seq = t1.seq
)
现在我可以根据需要获取确切的数据。 谢谢
,您只想要一个,而实际上并不在乎哪个,然后最大化t5的详细信息
select t1.name,t3.cat,t4.utt,t5.gcost,t5.net
from
(
select * from table_one
union all
select * from table_two) t1
LEFT JOIN table_three as t3 ON t3.id = t1.ct
LEFT JOIN table_four as t4 ON t4.id = t1.ct
left join (select gid,max(gcost) gcost,max(net) net from table_five group by gid) t5 on t5.gid = t1.id;
+--------------+------+------+-------+------+
| name | cat | utt | gcost | net |
+--------------+------+------+-------+------+
| Green Apple | A | AAA | 3000 | 6542 |
| Small Orange | B | BBB | 2560 | 6542 |
| Small Banana | C | CCC | 5800 | 6542 |
| Small Mango | C | DDD | 2560 | 6542 |
| Red Apple | A | AAA | 3000 | 6542 |
| Big Orange | B | BBB | 2560 | 6542 |
| Big Banana | C | CCC | 5800 | 6542 |
| Big Mango | C | DDD | 2560 | 6542 |
+--------------+------+------+-------+------+
8 rows in set (0.072 sec)