簡體   English   中英

Yii選擇多個條件表

[英]Yii select with multiple tables with conditions

我是yii的新手,如何使用yii進行此查詢?

查詢是:

從table1,table2,table3中選擇table1.userid作為userid,table2.name作為用戶名,table3.name作為游覽名稱,其中table1.userid = table2.id和table1.tid = table3.id按table1.weight,table1.result排序

謝謝萊斯利

您也可以為此使用Yii的查詢生成器

它看起來像這樣:

$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的更多信息,請參見此處。

伊涅薩是正確的。 這個問題最直接的答案是:

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的人際關系能力,以便可以更好地訪問此信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM