简体   繁体   中英

Yii select with multiple tables with conditions

I am fairly new in yii, how can I do this query with yii?

the query is:

select table1.userid as userid, table2.name as username, table3.name as tourname from table1, table2, table3 where table1.userid=table2.id and table1.tid=table3.id order by table1.weight, table1.result

Thanks, Leslie

You could also use Yii's Query Builder for that.

It would look something like this:

$results = Yii::app()->db->createCommand()
    ->select('t1.userid as userid,t2.name as username,t3.name as tourname')
    ->from('table1 t1')
    ->join('table2 t2','on'=> 't1.userid=t2.id') // could be ->leftJoin() as well
    ->join('table3 t3,'on'=>'t1.tid=t3.id')
    ->order('t1.weight,t1,result')
    ->queryAll()

Note that I've used joins instead of naming both tables in the where clause. These are two different ways of performing relational queries in SQL. Your method is called implicit joins and mine is called explicit join .

I used to write implicit joins but now I use mostly explicit joins as they are easier to maintain, read and change if needed.

More info on CDBCommand here.

Ineersa was correct. The most direct answer to the question is:

Yii::app()->db->createCommand("select table1.userid as userid, table2.name as username, table3.name as tourname from table1, table2, table3 where table1.userid=table2.id and table1.tid=table3.id order by table1.weight, table1.result")->queryAll();

But I think you should take advantage of Yii's ability to have relationships so that you can access this information better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM