如何在MySql中排除某些记录

时间:2012-05-18 06:54:31

标签: php mysql database

这是我的问题...对不起,如果对某些用户来说太简单了,我就是新手了。

我有三个数据库表,(idPerson),问题(idQuestion,答案), AskedQuestions (idPerson,idQuestion)。当我向用户提出问题时,我向AskedQuestions添加一行,以便我可以拥有注册表。

我遇到的问题是我必须选择一个随机问题,之前没有问过指定用户。

我一直在阅读几个小时,以便选择随机行的最佳方式,并分别如何查询以仅选择被询问的行,但还没有想到如何混合它们。

任何人都知道如何在 PHP和MySql 中执行此操作?我非常感激。 提前感谢社区,对不起我的英语,我的英语技能不是最好的!

问候

修改

我试图投票给你所有人,但我不能直到我有rep15,ahahhaa ......我忘记了一件事,因为我正在阅读,使用RAND()对表格进行全面扫描,在我的情况下是不可接受的,因为这些表是相当大的问题,关于500000条记录和AskedQuestions大概有1500000甚至更多......所以做RAND的时间太慢......

我需要这样的东西......加入问题并提出问题并排除那些idUser等于会话用户和idQuestion == idAskedQuestion ......并从那里选择一个随机的?

有没有办法做到这一点,在这种情况下,它会非常慢?

7 个答案:

答案 0 :(得分:2)

$res=mysql_query("select count(*) as number from question where idquestion not 
in(select idquestion from askedquestion where idperson='".$_session['id']."')");
$row=mysql_fetch_assoc($res);
$num=$row['number'];
//$num has no. of rows

$final_query="select * from question where idquestion 
not in(select idquestion from askedquestion 
where idperson='".$_session['id']."') limit ".rand(0,$num).",1";

它会选择不同的问题

答案 1 :(得分:1)

选择随机问题:

select * from question order by rand() limit 1

选择之前未提出的问题:

select * from question where idQuestion not in (select idQuestion from AskedQuestions)

组合:

select * from question 
where idQuestion not in (select idQuestion from AskedQuestions)
order by rand() 
limit 1

答案 2 :(得分:0)

您是否已尝试ORDER BY RAND()选择随机行,NOT IN仅匹配未提问题? 类似的东西:

SELECT q.idQuestion
FROM Question q
WHERE q.idQuestion NOT IN (SELECT aq.idQuestion FROM AskedQuestions aq WHERE aq.idPerson = 1)
ORDER BY RAND()

显然,用适当的值(可能是PHP变量)替换1。

答案 3 :(得分:0)

尝试:

SELECT * FROM Question, AskedQuestions WHERE AskedQuestions.idQuestion != Question.idQuestion AND AskedQuestions.idPerson = 'PERSON_ID' LIMIT 1

答案 4 :(得分:0)

尝试下面的查询

SELECT * FROM `Question` AS qs WHERE qs.idQuestion not in(SELECT aq.idQuestion FROM  
   AskedQuestions` AS aq WHERE aq.idPerson = loggedinUserID) ORDER BY RAND() LIMIT 0,1

如果您不想在查询中使用rand(),那么有一种方法..

   /*Select max and min id*/
   $range_result = mysql_query( " SELECT MAX(`idQuestion `) AS max_id , MIN(`idQuestion `) AS 
   min_id FROM `Question` ");

    $range_row = mysql_fetch_object( $range_result );

    $random = mt_rand( $range_row->min_id , $range_row->max_id );

   $result = mysql_query( " SELECT * FROM `Question` AS qs  WHERE qs.`idQuestion` >= $random  
    AND qs.idQuestion not in (SELECT aq.idQuestion From ASkedQuestions AS aq where  
    aq.idPerson   = loggedInUSerID) LIMIT 0,1 "); 

我希望它会对你有所帮助。

感谢

感谢

答案 5 :(得分:0)

到目前为止你做了什么?

你可以试试这个:

SELECT * Question q LEFT JOIN AskedQuestions a ON a.idQuestion = q.idQuestion WHERE a.idQuestion is null AND a.id AND a.idperson = 2 ORDER BY RAND() LIMIT 1;

答案 6 :(得分:0)

我已经调查了如何有效地选择随机行 。结果为here

对于您的情况,您有AUTO_INCREMENT吗?如果是这样,那么看看是否"案例:AUTO_INCREMENT有间隙,1行返回"将满足您的需求。请注意,过滤掉不需要的问题的WHERE条款会导致"空白"。

如果没有,则考虑FLOAT或UUID方法。要么应该做得很好,但可能需要一个列#34;随机"目的