【问题标题】:left join with ActiveRecord (yii2)左加入 ActiveRecord (yii2)
【发布时间】:2015-03-10 18:33:57
【问题描述】:

我尝试使用 LEFT JOIN 发送 SQL 请求,但它不显示来自 table2 表的数据。

public static function top($limit)
{
    return self::findBySql("
        SELECT * FROM table 1 g1 
        LEFT JOIN table2 s1 
        ON (g1.id = s1.g_id AND s1.id = (
            SELECT MAX(id) 
            FROM table2 s2 WHERE s2.g_id = g1.id
        )) 
        LIMIT :limit", 
    [':limit' => $limit]
    )->all();
}

【问题讨论】:

  • 您还需要将 table2 中的列添加到您的 select 子句中。
  • @PawełDuda,我试过了。我得到了同样的结果。
  • 试试这个:SELECT * FROM table 1 g1 LEFT JOIN table2 s1 ON (g1.id = s1.g_id) WHERE s1.id = ( SELECT MAX(id) FROM table2 s2 WHERE s2.g_id = g1.id ) 限制:限制
  • 在表中显示 DDL SQL。
  • 你的sql查询不正确。请参阅下面的答案。

标签: activerecord yii yii2


【解决方案1】:

您似乎正在将此函数添加到模型中,而 self 代表模型本身。

Yii 不会从另一个表返回结果,并且仅当您在模型上调用 find 时才会仅限于模型,而您需要使用如下 db 查询:

    $query = new \yii\db\Query;
    $query->select('*')
            ->from('table 1 g1')
            ->leftJoin('table2 s1', 's1.g_id AND s1.id = (SELECT MAX(id) FROM table2 s2 WHERE s2.g_id = g1.id')  
            ->limit($Limit);
    $command = $query->createCommand();
    $resp = $command->queryAll();

【讨论】:

    【解决方案2】:

    正确的 SQL 查询是

    SELECT * FROM table 1 g1 
            LEFT JOIN table2 s1 
            ON g1.some_field = s1.some_field
    

    其中 g1.some_field = s1.some_field 是定义连接的字段。

    【讨论】:

      【解决方案3】:

      我有类似...的工作代码:) 与 user 和 user_friend_list

                                       $query = new Query;
                                       $query  ->select(['user.id AS user_id', 'user_friend_list.id'])  
                                              ->from('user')
                                              ->innerJoin('user_friend_list', 'user.email = user_friend_list.email');
      
                                      $command = $query->createCommand();
                                      $data = $command->queryAll();
                                      foreach($data as $datakey)
                                      {
                                          //echo $datakey['id'];
                                          $friendfind = UserFriendList::findOne($datakey['id']);
                                          $friendfind->is_app_using_user_id=$datakey['user_id'];
                                          $friendfind->save();
                                      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-28
        • 2015-02-05
        • 1970-01-01
        • 1970-01-01
        • 2015-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多