Yii选择具有条件的多个表

时间:2014-06-11 13:46:59

标签: php yii

我在yii中相当新,我怎么能用yii做这个查询?

查询是:

  

选择table1.userid作为userid,table2.name作为用户名,table3.name作为tourname来自table1,table2,table3,其中table1.userid = table2.id和   table1.tid = table3.id by table1.weight,table1.result

谢谢, 莱斯利

2 个答案:

答案 0 :(得分:1)

Ineersa是对的。这个问题最直接的答案是:

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();

但我认为你应该利用Yii的能力建立关系,以便你能更好地获取这些信息。

答案 1 :(得分:1)

您也可以使用Yii的Query Builder

它看起来像这样:

$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()

请注意,我使用了连接,而不是在where子句中命名两个表。这些是在SQL中执行关系查询的两种不同方法。您的方法称为隐式连接,我的方法称为显式连接

我曾经写过隐式连接,但现在我主要使用显式连接,因为它们更容易维护,读取和更改(如果需要)。

此处有关CDBCommand的更多信息。