dongyishe6689 2018-03-16 11:15
浏览 155
已采纳

如何获取与MySQL数据库的多列值匹配的值

I need to match the multiple same column value of MySQL table using PHP and MySQL. I am explaining my table below.

db_user:

id      status    book_id

 1        0         22

 2        0         22

 3        1         22

 4        0         23

Here I need the select query and condition is if status=0 for same book_id means if table has lets say book_id=22 and all status=0 then only it will return value true otherwise false. I am writing one example below.

$sql=mysqli_query($connect,"select * from db_user where status=0 and....");
if(mysqli_num_rows($sql) > 0){
   $row=mysqli_fetch_array($sql);
   $data=$row['book_id'];
}else{
   return 0;
}

Here as per the example table only last row will fetch because for book_id=22 there is status=1 present. The data will only fetch when for one book_id all status=0.

  • 写回答

5条回答 默认 最新

  • doucandiao9180 2018-03-16 11:17
    关注

    One option uses aggregation to check the status values:

    SELECT book_id
    FROM db_user
    GROUP BY book_id
    HAVING SUM(CASE WHEN status <> 0 THEN 1 ELSE 0 END) = 0;
    

    We can also use EXISTS:

    SELECT DISTINCT t1.book_id
    FROM db_user t1
    WHERE NOT EXISTS (SELECT 1 FROM db_user t2
                      WHERE t1.book_id = t2.book_id AND t2.status <> 0);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器