Union queries from different databases in Laravel Query Builder(Laravel Query Builder 中来自不同数据库的联合查询)
问题描述
我在两个不同的数据库中有两个相似的表.两个表都有一个包含日期的列和一个包含电子邮件地址的列.虽然列名不一样.因此,我希望得到一个包含两个表中所有记录的结果.
I have two similar tables in two different databases. Both tables have a column with a date and one with email addresses. Though the column names are not the same. As result I want to have one result that contains all records from both tables.
所以我的第一步是:
$emails_1 = DB::connection('db1')->table('contacts_1')->select('mail_address AS email', 'date as created_at');
$emails_2 = DB::connection('db2')->table('contacts_2')->select('email', 'created_at');
所以现在我有两个结果,结果中的列名是相等的(email 和 created_at).
So now I have two results and the column names in the result are equal (email and created_at).
现在我想将结果合并在一起,所以我这样做了:
Now I want to merge the results together, so I do:
$all_emails = $emails_1->union($emails_2);
这是我得到错误的地方:
And this is where I get the error:
未找到基表或视图:1146 表 'db1.contacts_2' 不存在存在 (SQL: (select mail_address as email, date as created_atfrom contacts_1) union (select email, created_at fromcontacts_2))
Base table or view not found: 1146 Table 'db1.contacts_2' doesn't exist (SQL: (select
mail_addressasdateascreated_atfromcontacts_1) union (selectcreated_atfromcontacts_2))
因此,查询生成器似乎与不同的表混淆了.
So it seems that query builder gets confused with the diferente tables.
有人帮忙吗?
推荐答案
你不能使用不同的连接,但你仍然可以明确地提供数据库名称:
You can't use different connections, but you still can do it providing the db name explicitly:
$q1 = DB::table('db1.contacts')
// where(..) or anything you need here
->select('mail_address as email', 'date as created_at');
$q2 = DB::table('db2.contacts')
// like above
->select('email', 'created_at');
$result = $q2->union($q1)->get();
这篇关于Laravel Query Builder 中来自不同数据库的联合查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel Query Builder 中来自不同数据库的联合查询
基础教程推荐
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 在 SQL 中连接多个表 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 无法解决整理冲突 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
