thinkphp 5 implements UNION ALL 3 joint table queries, and brings search conditions, name, time, mobile phone number

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:

  1. Make sure that the database connection information and related models have been configured.

  2. 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-01the starting time you want, 手机号and the beginning of the mobile phone number you want to match.

  1. Finally, you can $resultobtain the results of the joint table query through variables.

table1Please note that , , table2, etc. in the code table3should be replaced with your actual table name, and column1, column2, column3etc. should be replaced with the field names you need to query. Make appropriate modifications and adjustments according to your actual situation.

Guess you like

Origin blog.csdn.net/qq_32450471/article/details/132357339