所以我的数据库中有两行 - user_one
和user_two
,这些行被用户ID占用作为邮件系统的编号,我还在同一邮件中包含了一个支持服务单系统功能,但我对此代码段有一些问题......
$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'";
正如您将注意到的那样,支持服务单ID为999
,并且只是检查这两个ID都不是999
时,此代码才能完美运行。虽然我还需要检查user_one
或user_two
的ID是999
还是999d
。这个当前代码返回1
,当我知道它应该返回0
时,所以我知道有些东西是出错的,我想我可能会错误地设置它。我试图以多种不同的格式设置它:
$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')";
但仍然得到相同的结果?任何人都可以告诉我这里我做错了什么,或者我如何让这段代码表现得更好?
答案 0 :(得分:5)
您需要使用括号来建立运算符优先级:
$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')";
答案 1 :(得分:3)
(user_one = '$user_id' AND user_two != '999')
OR (user_one = '$user_id' AND user_two != '999d')
...是一个问题,它简化为user_one = '$user_id'
,AND
条件变得无关紧要。
如果你不相信我,请尝试user_one = user_id
和user_two = '999'
行。它没有第一个括号内的条件,但是通过第二个并返回。
我假设你想要:
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。作为'999'
传递'999d'
或$user_id
仍会返回支持服务单。我非常喜欢这个功能,但如果不希望这样你可以使用:
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 :(得分:0)
尝试在查询中添加括号,如下所示:
$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')";