Using sub query for doubletts

You are viewing revision #2 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#1)

find doubletts by db fields. in this example i will check doublets for 3 tabelfields (col1,col2,col3). so i will get a subquery with the condition, select and grouping of the tablefields. the having with COUNT() > 1 means: find all records more then one result.

$model=new MyModel('search');
$model->unsetAttributes();
        
$criteria=new CDbCriteria();
$criteria->select='col1,col2,col3';
$criteria->group = 'col1,col2,col3';
$criteria->having = 'COUNT(col1) > 1 AND COUNT(col2) > 1 AND COUNT(col3) > 1';

get the subquery: the subquery is a part of the query i need.

$subQuery=$model->getCommandBuilder()->createFindCommand($model->getTableSchema(),$criteria)->getText();

the "real" criteria with the subquery. you can add some criteria you need.. important: the number of col and the result of the subquery must be the same size! add the subquery condition and order by tablefields:

$mainCriteria=new CDbCriteria();
$mainCriteria->condition=' (col1,col2,col3) in ('.$subQuery.') ';
$mainCriteria->order = 'col1,col2,col3';

how to use:

$result = MyModel::model()->findAll($mainCriteria);

or
$dataProvider = new CActiveDataProvider('MyModel', array(
        'criteria'=>$mainCriteria,
));
3 0
10 followers
Viewed: 25 533 times
Version: Unknown (update)
Category: Tips
Written by: mb
Last updated by: mb
Created on: Aug 7, 2012
Last updated: 11 years ago
Update Article

Revisions

View all history

Related Articles