相关文章推荐
` a ` LEFT JOIN ( SELECT * FROM ` b ` WHERE ` type ` = 2 ) AS b AND ( ` a ` . ` a ` = ` b ` . ` a ` AND ` a ` . ` b ` = ` b ` . ` b ` AND ` a ` . ` c ` = ` b ` . ` c ` ) OR ( ` a ` . ` a ` = ` b ` . ` a ` AND ` a ` . ` b ` = ` b ` . ` b ` AND ` a ` . ` d ` = ` b ` . ` d ` )

官方文档给的方法(子查询联接)

您可以使用 joinSub,leftJoinSub 和 rightJoinSub 方法加入查询的子查询。这些方法中的每一个都接收三个参数:子查询,其表别名和定义相关列的Closure:

$reminds = DB::table('hr')
            ->select('repeat_type_id',DB::raw('create_date as created_at'))
            ->where('valid',1)
            ->groupBy('repeat_type_id');
$repeat_types = DB::table('hrt')
            ->joinSub($reminds,'reminds_tables',function($join){
                $join->on('hrt.id','=','reminds_tables.repeat_type_id');
            ->get();
print_r($repeat_types);
select * from `hr` 
inner join (
	select `repeat_type_id`, create_date as created_at from `hrt` 
	where `valid` = 1 group by `repeat_type_id`) as `reminds_tables` 
`hrt`.`id` = `reminds_tables`.`repeat_type_id`

实现方法1:joinSub

$query = DB::table('table_name2')->where('type','=',2);
$info = DB::table('table_name')
            ->joinSub($query,'table_name2', function ($join) {
                $join->on([
                    ['table_name.a', '=', 'table_name2.a'],
                    ['table_name.b', '=', 'table_name2.b'],
                    ['table_name.c', '=', 'table_name2.c'],
                ])->orOn([
                    ['table_name.a', '=', 'table_name2.a'],
                    ['table_name.b', '=', 'table_name2.b'],
                    ['table_name.d', '=', 'table_name2.d'],
                ]);
            })->get();

joinSub 源码

文件地址:/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php

* AddHoneycombLog a subquery join clause to the query. * @param \Closure|\Illuminate\Database\Query\Builder|string $query * @param string $as * @param \Closure|string $first * @param string|null $operator * @param string|null $second * @param string $type * @param bool $where * @return \Illuminate\Database\Query\Builder|static * @throws \InvalidArgumentException public function joinSub($query, $as, $first, $operator = null, $second = null, $type = 'inner', $where = false) // 结果:query为原生sql,bindings为getBindings的绑定参数 // createSub方法见下方 [$query, $bindings] = $this->createSub($query); $expression = '('.$query.') as '.$this->grammar->wrapTable($as); $this->addBinding($bindings, 'join'); return $this->join(new Expression($expression), $first, $operator, $second, $type, $where); * Creates a subquery and parse it. * @param \Closure|\Illuminate\Database\Query\Builder|string $query * @return array protected function createSub($query) // If the given query is a Closure, we will execute it while passing in a new // query instance to the Closure. This will give the developer a chance to // format and work with the query before we cast it to a raw SQL string. if ($query instanceof Closure) { $callback = $query; $callback($query = $this->forSubQuery()); return $this->parseSub($query); * Parse the subquery into SQL and bindings. * @param mixed $query * @return array * @throws \InvalidArgumentException protected function parseSub($query) if ($query instanceof self || $query instanceof EloquentBuilder) { return [$query->toSql(), $query->getBindings()]; } elseif (is_string($query)) { return [$query, []]; } else { throw new InvalidArgumentException( 'A subquery must be a query builder instance, a Closure, or a string.' * AddHoneycombLog a binding to the query. * @param mixed $value * @param string $type * @return $this * @throws \InvalidArgumentException public function addBinding($value, $type = 'where') if (! array_key_exists($type, $this->bindings)) { throw new InvalidArgumentException("Invalid binding type: {$type}."); if (is_array($value)) { $this->bindings[$type] = array_values(array_merge($this->bindings[$type], $value)); } else { $this->bindings[$type][] = $value; return $this;

Laravel left join 多个条件用法

$query = EmailRecord::select($email_title_select);
$query->where($email_record_table.'.valid', 1);
$query->orderBy($email_record_table.'.id', 'desc');
$query->leftJoin($email_report_send_table." as send",function($join)use($email_record_table){
    $join->on('send.email_record_id',"=", $email_record_table.'.id')->where('send.valid',1);
});
if($contacts){
   $query->rightJoin($email_contact_link_table,function($join)use($contacts,$email_contact_link_table,$email_record_table){
       $join->on($email_record_table.'.id','=',$email_contact_link_table.'.email_record_id');
       $join->where($email_contact_link_table.'.valid',1);
       foreach ($contacts as $cont){
           $join->orWhere($email_contact_link_table.'.contact_name', 'like','%'.$cont.'%');
   });
}else{
   $query->leftJoin($email_contact_link_table,function($join)use($contacts,$email_contact_link_table,$email_record_table){
       $join->on($email_record_table.'.id','=',$email_contact_link_table.'.email_record_id')->where($email_contact_link_table.'.valid',1);
   });
                                    joinSub方法是Laravel框架中一个强大且灵活的查询语法。它允许我们在查询中嵌套子查询,并将其作为临时表与其他表进行联接。这种能力极大地增强了我们在数据库查询中的灵活性和表达能力。在本文中,我们深入了解了joinSub方法的使用。我们学习了它的基本语法,并通过一个示例演示了如何在Laravel应用程序中应用它。通过使用joinSub方法,我们可以避免在数据库中创建临时表,同时有效地处理数据。这种灵活性使我们能够更好地利用Laravel框架的强大功能。希望本文对你理解和使用Laravel中的。
use Illuminate\Support\Facades\DB;
$users = DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->select('users
                                    Laravel是一种流行的开源PHP Web应用程序框架,由Taylor Otwell在2011年创建并发布。它提供了一个简洁优雅的语法和丰富的功能集,旨在使Web开发过程更快速、简单和愉悦。MVC架构模式:Laravel采用了MVC(Model-View-Controller)架构模,将应用程序的逻辑分为不同的层,提高了代码的可维护性和可测试性。简洁的语法和表达力:Laravel框架支持具有简洁而表达力的语法,使得编写清晰、易读、易维护的代码成为可能。
                                    JoinClause 类是 Laravel 内部的一个类,用于构建 SQL 查询的 Join 子句。其中,Join 子查询是一种常用的查询方式,用于在查询中嵌套其他查询。方法接受多个参数,包括一个闭包、一个 QueryBuilder 实例或一个字符串,用于指定要嵌套的子查询。方法,我们可以方便地在 Laravel 中进行 Join 子查询操作,从而实现更复杂的数据库查询需求。参数用于指定主查询和子查询之间的关联条件,可以是一个字符串或一个闭包。参数是一个闭包,则创建一个新的查询实例,并通过。
    一张客户表,一张客户历史所属领导的表,在现在展示客户信息,要展示每条客户现在所属领导和上次所属领导
客户表                                              客户历史领导表
  id   name  sex a...
$dbExam = env('DB_EXAM_DATABASE', 'xxx');
        $dbLegal = env('DB_DATABASE', 'xxx');
        $data = DB::table($dbExam.'.x2_examhistory as emh')
                ->select(DB::raw('lli.name, lli.idcard, l
                                    sqlexplainSELECT `info_info`.*, `a`.`name` AS `d1name`FROM `info_info`LEFT JOIN (SELECT * FROM `common_diqu`) `a` ON a.id=d1 WHERE `status`=1ORDER BY `tid` DESCid  select_type     table   type    poss...
 
推荐文章