To implement three joint table queries (UNION ALL) with search conditions, name, time and mobile phone number in ThinkPHP 5, you can follow the steps below:
-
Make sure that the database connection information and related models have been configured.
-
Use
union()
the method to build 3 joint table queries while adding the required search criteria, name, time and mobile phone number in each query.
use think\Db;
// 构建第一个查询
$query1 = Db::table('table1')
->field('column1, column2, "table1" as source')
->where('name', 'like', '%关键词%')
->where('create_time', '>', '2023-01-01')
->where('phone', 'like', '手机号%');
// 构建第二个查询
$query2 = Db::table('table2')
->field('column3, column4, "table2" as source')
->where('name', 'like', '%关键词%')
->where('create_time', '>', '2023-01-01')
->where('phone', 'like', '手机号%');
// 构建第三个查询
$query3 = Db::table('table3')
->field('column5, column6, "table3" as source')
->where('name', 'like', '%关键词%')
->where('create_time', '>', '2023-01-01')
->where('phone', 'like', '手机号%');
// 合并查询并添加UNION ALL
$unionQuery = $query1->union($query2, true) // 设置为true以保留重复记录
->union($query3, true); // 设置为true以保留重复记录
// 获取查询结果
$result = $unionQuery->select();
In the above code, you need to replace table1
, table2
, table3
, and the corresponding fields, name, time and mobile phone number fields with the actual table names and field names. Replace the keywords 关键词
with the keywords you want to search for, 2023-01-01
the starting time you want, 手机号
and the beginning of the mobile phone number you want to match.
- Finally, you can
$result
obtain the results of the joint table query through variables.
table1
Please note that , , table2
, etc. in the code table3
should be replaced with your actual table name, and column1
, column2
, column3
etc. should be replaced with the field names you need to query. Make appropriate modifications and adjustments according to your actual situation.