2017-04-27 1547 views
-1

enter image description here如何使用不等於查詢在Yii2

我有兩個表ad_pool和廣告。 ad_pool有一些數據,而廣告是空的。我使用這段代碼從第一個表中選擇不等於這個和這個(''','fisttablekey','second_tbl_key'])的查詢。這是我用來檢索數據的完整代碼,我也上傳了圖像。

$pool1 = (new Query())>select('p.id,p.cleaner_user_id,p.ad_place_id') 
        ->from('ad_pool p') 
        ->innerJoin('advertisment a' , 'p.id = a.pool_id') 
       ->where(['=','ad_place_id',1]) 
       ->andWhere(['<>','p.id','a.pool_id']) 
       ->orderBy(new Expression('rand()')) 
       // ->limit(1) 
       ->all(); 
        var_dump($pool1); 
        exit(); 

這回我空數組。需要你的幫助。提前致謝。

+1

用'createCommand() - > rawSql'替換'all()'並在數據庫控制檯中運行它的輸出以查看是否得到任何結果。 – Bizley

+0

它給了我這個錯誤...語法錯誤,意外的'返回'(T_RETURN) –

回答

2

INNER JOIN關鍵字選擇兩個表中具有匹配值的記錄。 由於你的廣告是空的,它不會返回任何數據。您可以改用LEFT JOIN。

$pool1 = (new Query())>select('p.id,p.cleaner_user_id,p.ad_place_id') 
        ->from('ad_pool p') 
        ->leftJoin('advertisment a' , 'p.id = a.pool_id') 
       ->where(['=','ad_place_id',1]) 
       ->andWhere(['<>','p.id','a.pool_id']) 
       ->orderBy(new Expression('rand()')) 
       ->all(); 

W3Schools Reference

+0

你有沒有嘗試過使用活動記錄?包括一個方法getAdvertisements() –

+0

是的,這是問題所在。我想從第一個表中檢索數據,但需要檢查其ID是否已經存在,然後忽略該數據。我怎樣才能做到這一點?你能否爲我提供任何解決方案 –

+0

nope我沒有試過。 –

0

This way i solved this problem after whole day search

這樣我解決後3〜4小時勤勞這個問題。從第二個表中獲取所需的值(如果存在),然後將其轉換爲單個數組並在NOT IN條件下使用它。 (我們必須熱衷於幫助別人,我們應該互相幫助)。