1

How do you write this SQL query in Yii2?

SELECT * FROM table
WHERE column1 IN (SELECT column2 FROM table WHERE column1 = 5)
arogachev
  • 33,150
  • 7
  • 114
  • 117
Eric W
  • 31
  • 1
  • 4

5 Answers5

3

Let's say your model named YourModel representing table with name table. Then the query will be:

$subQuery = YourModel::find()->select('column2')->where(['column1' => 5]);
$query = YourModel::find()->where(['column1' => $subQuery]);
$models = $query->all();

Also similar question was asked before.

Community
  • 1
  • 1
arogachev
  • 33,150
  • 7
  • 114
  • 117
0
Yii::$app->db->createCommand('SELECT * FROM table
       WHERE column1 IN (SELECT column2 FROM table WHERE column1 = :val)', [':val' => 5])->queryAll();

Will return associative array, like ['id' => 1, 'name' => 'Victor']

0

Yii2 SubQuery:

$query=YourBaseModel::find()->select('p_id');
$subquery=YourSubMOdel::find()->Where(['in','p_id',$query])->andWhere(['column1'=>1])->one();

$query=>select the p_id value in YourBaseModel. p_id value stored in $query variable. And then check the $query value in YourSubModel.

0

You can do it:

$query = 'SELECT * FROM table
          WHERE column1 IN (SELECT column2 FROM table WHERE column1 = 5)';

$list = $model::findBySql($query)->all();

Or:

$subquery = $model::find()->select('column1');
$query = $model::find()->where(['not in',$subquery])->all();

In this case it's the same. I hope I help you

ivan martinez
  • 186
  • 1
  • 8
0

This is a lot of ways for solving your issue. I will give an example of the most correct, in terms of use the yii2 framework.

SQL:

SELECT * 
FROM table 
WHERE 
    column1 IN 
    (SELECT column2 
        FROM table
        WHERE column1 = 5)

Yii2 activerecord:

$subQuery = TableModel::find()->select('column2')->where(['column1' => 5]);
$result = TableModel::find()->where(['IN', 'column1', $subQuery])->all();
Andrinux
  • 364
  • 5
  • 9