【问题标题】:How to get some rows from 2 tables如何从 2 个表中获取一些行
【发布时间】:2015-04-28 18:19:51
【问题描述】:

我有 2 个表,我需要从表 2 中获取与表 1 具有相同键的所有行。

这是一个例子:

Table1                    Table2
ID  |   Name             ID |  Brand   |  tabel1_id
1   |   Razvan           1  |  Ford    |  1
2   |   Becker           2  |  VW      |  1
                         3  |  Renault |  1
                         4  |  Dacia   |  2

结果需要是一个数组:

array(
"Razvan"=> 
          array('Ford','VW','Renault'),
"Becker"=>
         array('Dacia'));

我使用了正确的 JOIN 但没有工作;

  $resursa=DB::table('table1')
        ->rightJoin('table2', 'table1.d', '=', 'table2.table1_id')
        ->select('table1.*','table2.*')
        ->groupBy('table1.d')
        ->get();
    return view('home',array('resurse'=>$resursa));

非常感谢!!!

【问题讨论】:

  • 到目前为止你做了什么?你的代码呢?
  • 请显示您尝试过的查询“不工作”。解释一下“不工作”是什么意思。
  • 它不工作是什么意思?错误是什么?
  • 只显示表 2 中对应 table1 id 的第一个元素

标签: php mysql laravel join


【解决方案1】:

我无法评论,所以我必须写一个答案:

您的查询中有错字:

 ->rightJoin('table2', 'table1.d', '=', 'table2.table1_id')

应该是

 ->rightJoin('table2', 'table1.id', '=', 'table2.table1_id')

如果 Query builder 中有 rightJoin 函数,那将是正确的。但是你需要改用 leftJoin,像这样:

 $resursa=DB::table('table2')
    ->leftJoin('table1', 'table2.table1_id', '=', 'table1.id')
    ->select('table1.*','table2.*')
    //->groupBy('table1.id') // you can't groupby to get the result you wish for
    ->get();
return view('home',array('resurse'=>$resursa));

【讨论】:

    【解决方案2】:

    如果我正确理解了您的问题,正确的查询是这样的:

    SELECT * FROM Table1
    LEFT JOIN Table2 ON Table1.ID=Table2.tabel1_id
    

    要获得你问的数组,我会做类似的事情

    while ( $row=mysql_fetch_assoc(...))
    {
        $array[$row['Name']]=$row['Brand']
    }
    

    【讨论】:

      【解决方案3】:

      SQL:

      Select t1.Name as colName , t2.Brand as colBrand FROM Table2 t2 INNER JOIN Table1 t1 on t2.table1_id = t1.ID;
      

      PHP 假设您将获得关联行。

      $output_array = array();
      while($row = mysql_fetch_assoc($result))
      {
         if(!isset($output_array[$row['colName']]))
         {
             $output_array[$row['colName']] = array();
         }
         $output_array[$row['colName']][] = $row['colBrand'];
      }
      

      【讨论】:

        【解决方案4】:

        select GROUP_CONCAT(DISTINCT B.Brand) from table2 as B, table1 as A where A.id=B.table1_id group by B.table1_id。

        您将获得 2 行并获取并使用爆炸您将获得数组

        【讨论】:

          猜你喜欢
          • 2013-07-15
          • 2018-10-22
          • 2019-11-26
          • 1970-01-01
          • 2019-04-01
          • 2023-03-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多