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条)

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条