繁体   English   中英

如何针对不同的数据库执行具有不同列名的相同查询以获得单个结果/数据集

[英]How to execute same queries with different column names against different databases to get single result/data set

在此处输入图像描述

如您所见,我有多个数据库( db10, db12 ),每个数据库都包含单独的客户数据。

我想查询存储在货币表中的货币的时间序列数据。

查询是

Select 卢比,日元来自 db10.currency 其中 dateTime 在 value1 和 value2 之间;

结果

在此处输入图像描述

它对一个数据库运行良好

但我想处理针对不同数据库的多个查询。

例如。

Select Rupee, Yen from db10.currency where dateTime between value1 and value2;
Select Dollar, Pound from db12.currency where dateTime between value1 and value2;

等等。

请注意,我动态生成这些查询。 所有不同的信息,例如 customerId、value1、value2,将作为有效负载从Front传递到Backend 我使用有效负载并动态进行这些查询。

我最初虽然它可以使用UNION ALL如下

Select Rupee, Yen from db10.currency where dateTime between value1 and value2 
UNION ALL 
Select Dollar, Pound from db12.currency where dateTime between value1 and value2;

但最近我发现它需要相同的列名,以相同的顺序工作。 不幸的是,我有不同的专栏,例如。 卢比,日元,美元,英镑,所以它不起作用。

我想知道处理此类查询的最佳和高性能方法。

预期结果如下所示(如果您可以提出其他建议,则更好)

在此处输入图像描述

如果数据库在同一台服务器上,并且您有一个将用于连接条件的列,则可以这样做,在您的情况下,我看到 dateTime。

尝试:

SELECT db10.Rupee,
       db10.Yen,
       db20.Dollar,
       db20.Pound
FROM db10.currency
INNER JOIN db20.currency ON db10.currency.dateTime = db20.currency.dateTime 
WHERE dateTime between value1 and value2;
  1. 缺少条件的地方。 我想根据日期过滤数据集。

编辑并添加到查询中。

  1. 我不确定内部连接是否是正确的子句。 假设对于给定的日期范围,如果数据不存在于 db12.currency 但存在于 db10.currecy 中,则返回空数据集。 期望它应该为不可用的数据返回 null

这是一个关于如何做到这一点的演示,请改用 LEFT JOIN。

  1. 如果我有更多的数据库和第三位客户的货币表怎么办?

同上添加另一个连接条件

这里左连接将从左表中获取数据。 如果对于给定的日期范围,左表没有数据但右表有一些数据怎么办? 我不能 go 与左/右/内连接。 要求是我想获取单个查询的记录并在单个集合中返回结果。 如果在任何表中,数据不可用,则必须在该列中返回 null 值

在这种情况下,您需要 MySQL 不支持的完全外部连接,但您可以模拟它:

https://stackoverflow.com/questions/4796872/how-can-i-do-a-full-outer-join-in-mysql#:~:text=We%20can%20emulate%20it%20by,t2%60 %20ON%20%60t1%60

https://www.geeksengine.com/database/multiple-table-select/full-join.php

SELECT db10.Rupee,
       db10.Yen,
       db20.Dollar,
       db20.Pound
FROM db10.currency
LEFT JOIN db20.currency ON db10.currency.dateTime = db20.currency.dateTime 
WHERE dateTime between value1 and value2
UNION
SELECT db10.Rupee,
       db10.Yen,
       db20.Dollar,
       db20.Pound
FROM db10.currency
RIGHT JOIN db20.currency ON db10.currency.dateTime = db20.currency.dateTime 
WHERE dateTime between value1 and value2;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM