dongrong9053 2016-01-04 13:43
浏览 94
已采纳

MySQLi!=没有处理多个AND / OR子句

So I have two rows in my Database - user_one and user_two, these rows are occupied by User ID's as numbers for a messaging system, I have also included a support ticket system within the same message feature but am having a few issues with this code snippet...

$sqlc="SELECT * FROM ap_conversations WHERE user_one = '$user_id' AND user_two != '999' OR user_two = '$user_id' AND user_one != '999' OR user_one = '$user_id' AND user_two != '999d' OR user_two = '$user_id' AND user_one != '999d'";

As you'll notice, the support tickets ID is 999, and when it was kept to just checking that neither ID's were 999 this code worked perfectly. Although I also need it to check that neither user_one or user_two has ID's of 999 or 999d. This current code returns 1, when I know for a fact it should return 0 so I know something is defiantly going wrong and I think I may have it set up incorrectly. I have attempted to set it up like this in many different formats:

$sqlc="SELECT * FROM ap_conversations WHERE user_one = '$user_id' AND (user_two != '999' OR user_two != '999d') OR user_two = '$user_id' AND (user_one != '999' OR user_one != '999d')";

But still get the same results? Can anybody tell me what I am doing wrong here or how I can make this code perform better?

  • 写回答

3条回答 默认 最新

  • douyan1970 2016-01-04 14:05
    关注
       (user_one = '$user_id' AND user_two != '999')
    OR (user_one = '$user_id' AND user_two != '999d') 
    

    ...is a problem, it simplifies to user_one = '$user_id', the AND conditions become irrelevant.

    If you don't believe me, try a row where user_one = user_id and user_two = '999'.. It fails the first bracketed condition, but passes the second and is returned.

    I assume you want:

    SELECT * FROM ap_conversations 
     WHERE (user_one = :user_id AND user_two NOT IN ('999','999d')) 
        OR (user_two = :user_id AND user_one NOT IN ('999','999d'));
    

    N.B. Passing in '999' or '999d' as the $user_id will still return the support tickets. I quite like this functionality but if this is not desired you could use:

    SELECT * FROM ap_conversations 
     WHERE (user_one = :user_id OR user_two = :user_id) 
       AND user_one NOT IN ('999','999d')
       AND user_two NOT IN ('999','999d');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。