【问题标题】:How to check that one specific value is exist in first coumn or second column in sql?如何检查sql的第一列或第二列中是否存在一个特定值?
【发布时间】:2019-08-16 04:22:51
【问题描述】:
  1. 我只有一个值。现在,我想检查值是否存在于 'from_user_id' 列或 'to_user_id' 列,然后我想 返回包含该值的最后一条记录,该值将在 “from_user_id”或“to_user_id”列。

    $query3 = $this->db->query("select * from message where 26 
    IN(from_user_id,to_user_id) desc limit 1");
    foreach($query3->result() as $row)
    {
       $message = $row->message;
    }
    

    这个我试过了,但是没用。

    $query3 = $this->db->query("select * from message where 26 
    IN(from_user_id,to_user_id)");
    
    foreach($query3->result() as $row)
    {
        $message = $row->message;
    } 
    

    我也试过这个没有给我最后的记录。

【问题讨论】:

  • IN() 包含要查找的值,$str[$i] 是您要查找的字段,您只需要两个 OR where 条件
  • 最后一条记录然后应用order by和top 1

标签: php sql codeigniter


【解决方案1】:
SELECT * 
FROM message 
WHERE from_user_id = 26 OR to_user_id = 26
ORDER BY id DESC
LIMIT 1

假设,在您的消息表中,您有整数主键作为 id。如果没有,请将 order by 语句更新到正确的字段

【讨论】:

    【解决方案2】:

    这很容易检查

     $this->db->where('from_user_id', 26);
     $this->db->or_where('to_user_id', 26);
     $result = $this->db->get('message')->result();
    
     if(isset($result) && count($result) > 0){ 
         foreach($result as $row)
         {
            $message = $row->message;
         }
      }else{
         echo 'No result found';  
      }
    

    【讨论】:

      【解决方案3】:

      你可以像这样创建一个活动记录:

      $id = 26;
      $this->db->where('from_user_id', $id)
          ->or_where('to_user_id', $id)
          ->order_by('message_id','desc')
          ->limit(1);
      $query3 = $this->db->get('message')->row();
      
      if (!empty($query3)) {
          $message = $query3->message;
      } else {
          echo 'No message found!';
      }
      

      message_id 是消息表 ID。

      【讨论】:

      • 使用join是什么意思?你在哪里加入?
      • 您还想使用查询生成器(活动记录)还是仅使用本机查询?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      • 2015-06-03
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多