选择一个尚未显示的随机结果

时间:2012-07-02 23:35:14

标签: php mysql sql codeigniter

任何能够帮助我的人都将不胜感激。

目标:我想随机显示一个表中的id,以确保当前用户没有看到它。

两个表:offershas_seen

我想从优惠中选择一个随机ID,然后根据has_seen表进行检查。

如果has_seen中存在ID,则需要重新选择另一个随机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 ");

5 个答案:

答案 0 :(得分:1)

我认为这可以通过执行左连接然后检查null来在纯SQL中实现。

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

答案 1 :(得分: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;
    }
}

答案 2 :(得分:0)

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

答案 3 :(得分: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

答案 4 :(得分:0)

感谢您的回答。我重复了它将被带到用户的方式,并相信当我的网站上有数百人同时使用新方法时效率更高。

谢谢!