Yii2:如何编写Mysql查询以使用左连接从两个表中选择记录

时间:2015-04-16 11:18:16

标签: mysql yii2 yii2-advanced-app

我有两张桌子,我想加入...即营地&城市。 我已经用PHP写了这个查询......但是我想要Yii2格式的相同查询...请告诉我如何在yii2中编写这个查询... ??

以下是我的问题:

SELECT DISTINCT camps.city_id, camps.state_id, cities.city_name 
    from camps 
    LEFT JOIN cities
    ON cities.state_id = camps.state_id
    WHERE camps.state_id = 5
    AND camps.status = '1'
    ORDER BY cities.city_name ASC

4 个答案:

答案 0 :(得分:4)

use yii\db\Query;

$query  = new Query(); 
$query->select
                       (['camps.city_id AS City, camps.state_id AS State, cities.city_name AS Name'
                       ]) 
                      ->from('camps')
                      ->join('LEFT JOIN',' cities','cities.state_id = camps.state_id')
                      ->where('camps.state_id=:id',['id'=>5])
                      ->andWhere('camps.status=:no',['no'=>1]);


 $command   = $query->createCommand();
 $result    = $command->queryAll(); 

答案 1 :(得分:1)

ActiveQuery的等价物可以是这样的:

Camp::find()
    ->select(['city_id', 'state_id', 'city_name'])
    ->distinct()
    ->joinWith('city')
    ->where([
        'state_id' => 5,
        'status' => 1,
    ])
    ->orderBy(['city_name' => SORT_ASC])
    ->all();

并添加与Camp模型的关系:

public function getCity()
{
    $this->hasOne(City::className(), ['state_id' => 'state_id']);
}

您可以在Active Record section中找到文档:

答案 2 :(得分:0)

$query = new Query();
    $query->select(['camps.city_id', 'camps.state_id',   'cities.city_name'])->
        from('cities')->
        innerJoin('camps','cities.state_id = camps.state_id')->
        where(['camps.state_id' => 5,'camps.status' => '1'])->all();

答案 3 :(得分:0)

使用此功能,我希望这会对您有所帮助

$sql = " SELECT DISTINCT camps.city_id, camps.state_id, cities.city_name 
from camps 
LEFT JOIN cities
ON cities.state_id = camps.state_id
WHERE camps.state_id = 5
AND camps.status = '1'
ORDER BY cities.city_name ASC ";

$query = Yii::$app->db->createCommand($sql)->execute();