【发布时间】:2021-05-27 07:12:00
【问题描述】:
我可以SELECT来自两个数据库的数据(具有适当的用户权限):
SELECT *
FROM test1.table1 AS t1
INNER JOIN test2.table2 AS t2 ON (t2.id = t1.id);
这将返回以下结果:
+----+-------+----+------------------------------------------+
| id | db | id | info |
+----+-------+----+------------------------------------------+
| 1 | test2 | 1 | Success if test2 db name was not static. |
+----+-------+----+------------------------------------------+
但是,我需要更改 INNER JOIN test2.table2 以在单个查询中使用 test1.table1.db 中指定的数据库。 db 可以根据JOIN 动态变化,所以我不能事先写。
如何使用一个数据库名称作为行值存储到JOIN 两个数据库中使用单个查询?
不幸的是,我没有特权来辩论这个优点。此外,我尝试了几个 MariaDB 小提琴,但都没有工作,所以这是我正在使用的测试代码:
数据库test1:
CREATE DATABASE `test1` /*!40100 COLLATE 'utf8mb4_unicode_520_ci' */
CREATE TABLE `table1` (`id` INT(11) NOT NULL AUTO_INCREMENT,
`db` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_520_ci', PRIMARY KEY (`id`) USING BTREE)
COLLATE='utf8mb4_unicode_520_ci'
ENGINE=InnoDB;
INSERT INTO `table1` (`id`, `db`) VALUES (1, 'test2');
数据库test2:
CREATE DATABASE `test2` /*!40100 COLLATE 'utf8mb4_unicode_520_ci' */
CREATE TABLE `table2` (`id` INT(11) NOT NULL AUTO_INCREMENT,
`info` VARCHAR(255) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_520_ci', PRIMARY KEY (`id`) USING BTREE)
COLLATE='utf8mb4_unicode_520_ci' ENGINE=InnoDB;
INSERT INTO `table2` (`id`, `info`) VALUES (1, 'Success if test2 db name was not static.');
【问题讨论】:
-
为什么有两个数据库?
-
Unfortunately I'm not in the privileged position to debate the merit of this.