[英]Laravel mysql union of multiple tables
I have multiple identical mysql database tables . 我有多个相同的 mysql数据库表 。
What I need is a raw sql or Laravel schema to get the Union of all the tables in the database except the one's that are not identical. 我需要的是原始sql或Laravel模式,以获取数据库中所有表的联合 (除了不相同的表)。
I already tried the following code 我已经尝试了以下代码
$multipleUnion = DB::table('teble_1')->union(DB::table('teble_2')->union(DB::table('teble_3')))->get();
but I got this error 但是我得到这个错误
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;
SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'union (select * from
table_3
))' at line 1 (SQL: (select * fromtable_1
) union ((select * fromtable_2
) union (select * fromtable_3
)))在第1行(SQL:(select * from
table_1
)union((select * fromtable_2
))中,检查与您的MySQL服务器版本相对应的手册,以在'union(select fromtable_3
))附近使用正确的语法。 *来自table_3
)))
I don't want to query like 我不想查询
SELECT * FROM table_1 UNION SELECT * FROM table_2 UNION SELECT * FROM table_3
Because the number of tables can increase as the time goes. 因为表的数量会随着时间的流逝而增加。 Thanks in Advance.
提前致谢。
Try this: 尝试这个:
$multipleUnion = DB::table('teble_1')->union(DB::table('teble_2'))
->union(DB::table('teble_3'))->get();
Creating a query from an array of table names: 从表名数组创建查询:
$query = DB::table($tables[0]);
foreach(array_slice($tables, 1) as $table) {
$query->union(DB::table($table));
}
$multipleUnion = $query->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.