2012-07-02 42 views
2

任何人都可以幫助我將不勝感激。選擇一個未顯示的隨機結果

目標:我想從一個表中隨機顯示id,以及確保當前用戶沒有看到它。

兩個表:offershas_seen

我想選擇一個隨機ID從報價,檢查對has_seen表。

如果ID存在於has_seen中,它需要重新挑選另一個隨機ID。當前會話的任何一個用戶永遠不會看到相同的ID。

我似乎無法弄清楚如何選擇一個隨機的,檢查其他表,並找回如果返回。

我已經試過這

$query = $this->db->query("SELECT * FROM ".$this->offer_table." WHERE NOT EXISTS (SELECT * FROM ".$this->shown_table." WHERE ".$this->shown_table.".camp_id = ".$this->offer_table.".camp_id AND ".$this->shown_table.".usercode = ".$this->session->userdata("table")." LIMIT 1 "); 
+1

你嘗試過什麼嗎? –

+0

我試過這個:'$ query = $ this-> db-> query(「SELECT * FROM」。$ this-> offer_table。「WHERE NOT EXISTS(SELECT * FROM」。$ this-> shown_table。「WHERE」 。$ this-> shown_table。「。camp_id =」。$ this-> offer_table。「。camp_id AND」。$ this-> shown_table。「。usercode =」。$ this-> session-> userdata(「table」) 。「LIMIT 1」);'是的,我使用的是codeigniter,但直接的mysql會沒事的。 – user1497363

回答

0

這裏是你如何能使用CI的DB類做到這一點:

// the maximum ID that is acceptable 
$max = $this->db->get('first_table')->count(); 

while(true) { 
    // get a random number 
    $randomID = rand(0,$max); 

    // the condition for which we will check the has_seen table 
    $condition = array(
     'id' => $randomID 
    ); 

    // if count is 0, it has not been seen. We add it to the table and return 
    // if it has been seen, the loop will repeat 
    if ($this->db->get_where('has_seen', $condition)->count() === 0) { 
     $this->db->insert('has_seen', array(
      'id' => $randomID 
     )); 
     return $randomID; 
    } 
} 
+0

把你的代碼放在我得到後感興趣:'致命錯誤:調用未定義的方法CI_DB_mysql_result :: count()',我自動加載自動配置中的db類 – user1497363

1

我覺得做一個左側,這可以在普通的SQL實現連接,然後檢查null。

沿東西線的

SELECT * FROM table1 LEFT JOIN table2 USING (shared_key) WHERE table2.id IS NULL ORDER BY rand() LIMIT 1 
+0

我在'where子句'中得到了一個未知列'ya2x8',雖然我翻了一番檢查它。 – user1497363

+0

您可以將您的表結構添加到您的問題中。 –

0
SELECT * FROM `offers` WHERE `camp_id` NOT IN (SELECT `camp_id` FROM `has_seen` WHERE `user code` = 1) ORDER BY RAND() LIMIT 1 
+0

經過編輯匹配我的表我在'where子句'中得到一個未知列'ya2x8',雖然我加倍檢查它的存在 – user1497363

0

我總是喜歡讀表的內容到一個數組中,並從那裏與他們合作。根據你打算如何使用結果,你可以減少數據庫訪問,只讀一次,然後從數組中讀取數據(然後,我假設,爲下一個會話更新has_seen表)。

我必須爲僞代碼道歉,因爲我已經寫了任何PHP已經有多年了。

一旦你得到了你的陣列,該算法是這樣的:

var array 
var end = array.length 

function getNextRandomUnseen 
{ 
    var i = rand(end) 
    var temp = array[i] 
    array[i] = array[end--] 
    return temp 
} 

如果你願意,你甚至可以在陣列的堅持到底的可見值,所以它們不會丟失。

array[end+1] = temp 
0

感謝您的回答。我重新調整了它將被帶給用戶的方式,並且認爲新方式一次對我網站上的數百人提供了更高的效率。

謝謝!