【问题标题】:How to do a self join in laravel resulting in distinct values如何在laravel中进行自我加入导致不同的值
【发布时间】:2015-08-15 17:04:06
【问题描述】:
ID|user_id   |book_id   |author
1 |8         |7         |bill
2 |8         |6         |sally
3 |3         |7         |rob
4 |3         |4         |sarah
5 |3         |6         |jane
6 |8         |7         |frank

我想要实现的是 user_id 8 book_ids 与 user_id 3 book_id 匹配的行。但只选择了 user_8s 行。并且由 book_id 区分。所以我希望结果是:

第 1 行, 第 2 行

到目前为止,我有这个但不幸的是我一直得到第 6 行以及第 2 行和第 1 行。基本上我希望结果与 book_id 不同,但我不确定如何做到这一点。

$check = DB::table('table as u1') 
->join('table as u2','u1.book_id', '=', 'u2.book_id')
->where('u2.user_id', 8)->where('u1.user_id', 3)
            ->get();

【问题讨论】:

    标签: sql laravel eloquent


    【解决方案1】:

    一个适当的(与其他数据库兼容并启用ONLY_FULL_GROUP_BY,在 MySQL 5.7 中默认启用)等效 MySQL 查询以获得所需的结果是

    SELECT t.*
      FROM
    (
      SELECT MIN(t1.id) id
        FROM table1 t1 JOIN table1 t2
          ON t1.book_id = t2.book_id
       WHERE t1.user_id = 8
         AND t2.user_id = 3
       GROUP BY t1.user_id, t1.book_id  
    ) q JOIN table1 t
        ON q.id = t.id
    

    输出:

    |身份证 |用户 ID | book_id |作者 | |----|---------|---------|--------| | 1 | 8 | 7 |账单 | | 2 | 8 | 6 |莎莉 |

    这是一个SQLFiddle演示

    使用 Laravel Query Builder 会如下所示

    $subquery = DB::table('table as t1')
        ->join('table as t2', 't1.book_id', '=', 't2.book_id')
        ->where('t1.user_id', 8)
        ->where('t2.user_id', 3)
        ->groupBy(['t1.user_id', 't1.book_id'])
        ->select(DB::raw('MIN(t1.id) as id'));
    $check = DB::table('table as t')
        ->join(DB::raw("({$subquery->toSql()}) as q"), 't.id', '=', 'q.id')
        ->mergeBindings($subquery)
        ->select(['t.id', 't.user_id', 't.book_id', 't.author'])
        ->get();
    

    【讨论】:

      【解决方案2】:

      你有两个选择。您可以使用distinct()groupBy()

      变体 1:

      $check = DB::table('table as u1')
          ->join('table as u2','u1.book_id', '=', 'u2.book_id')
          ->where('u2.user_id', 8)->where('u1.user_id', 3)
          ->distinct()
          ->get();
      

      变体 2:

      $check = DB::table('table as u1')
          ->join('table as u2','u1.book_id', '=', 'u2.book_id')
          ->where('u2.user_id', 8)->where('u1.user_id', 3)
          ->groupBy('u1.book_id')
          ->get();
      

      【讨论】:

      • 我认为它可能是 groupBy(变体 2),但由于某种原因,我只得到第 1 行。变体 1 我得到第 1、2 和 6 行。
      • @Billy 将 group by 从 user_id 更改为 u1.book_id
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-19
      • 1970-01-01
      • 2012-04-10
      相关资源
      最近更新 更多