dongpo2340 2012-07-11 11:43
浏览 106
已采纳

如何在mysql_query返回的数组中找到一些值

I have voting system in my site and i want to check that user has upvoted,downvoted or not. To reduce the no. of queries i selected complete table containing id equals to user id from voting table table schema for vote table is Vote table table schema for answer table is answer table

$query=SELECT answer_id,user_id,vote FROM vote WHERE user_id='{$_SESSION["id"]}'
$result1=mysql_query($query);
$array=mysql_fetch_array($result1);

now when i fetch the answers of question i want to check that if this user has voted or not if answer_id has found in this array than than i want to find the value of vote ?

code is

$query1="SELECT * FROM answers WHERE question_id='{$question_id}'";//$question_id is id of question
$result=mysql_query($query1);
if($result){
    While ($row=mysql_fetch_arrar($result)){
        if(in_array($row["id"],$array){
            echo $array["vote"];
        }
    }
}

I am confused how to fetch two array together...?This query only works for first value because i am not using while loop in $array,Can anybody help me..?

  • 写回答

1条回答 默认 最新

  • dongyu1125 2012-07-11 14:04
    关注

    This can be done in one query to determine if a user has voted for an answer. There is no need for a preliminary query to get user votes, or an array comparison inside the fetch loop.

    Use a LEFT JOIN against a subquery on votes and supply the userid in its WHERE clause. If the value of uservotes.vote is NULL, the user has not voted for this answer. Otherwise, uservotes.vote will contain the user's vote.

    SELECT
      answers.*,
      uservotes.vote
    FROM 
      answers 
      LEFT JOIN (
        SELECT answer_id, vote FROM votes WHERE user_id = '{$_SESSION["id"]}'
      ) uservotes ON answers.id = uservotes.answer_id
    WHERE answers.question_id = {$question_id}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 复现论文:matlab仿真代码编写
  • ¥15 esp32驱动GC9A01循环播放视频
  • ¥15 惠普360g9的最新bios
  • ¥30 这个功能用什么软件发合适?
  • ¥60 微信小程序,取消订单,偶尔订单没有改变状态
  • ¥15 用pytorch实现PPO算法
  • ¥15 关于调制信号的星座图?
  • ¥30 前端传参时,后端接收不到参数
  • ¥15 这是有什么问题吗,我检查许可证了但是显示有呢
  • ¥15 机器学习预测遇到的目标函数问题