如何从查询结果中排除相等的值

时间:2012-10-08 19:39:52

标签: php mysql sql database

我有这个问题:

SELECT queue.first_dealer, queue.second_dealer, queue.status
FROM queue
WHERE queue.status = 3
AND queue.first_dealer = $user_id
OR queue.second_dealer = $user_id
AND queue.status = 3
ORDER BY id DESC
LIMIT 5

但有时first_dealer或second_dealer可以是相同的,如果它们是相同的,我想跳到下一个记录。

3 个答案:

答案 0 :(得分:0)

您需要在WHERE子句中添加一些括号,因为AND和OR之间有[operator precedence][1]。组合在一起的条件,如下:

SELECT queue.first_dealer, queue.second_dealer, queue.status
FROM queue
WHERE queue.status = 3
AND ( queue.first_dealer = $user_id 
      OR queue.second_dealer = $user_id)
AND queue.status = 3 AND 
queue.first_dealer <> queue.second_dealer
ORDER BY id DESC
LIMIT 5

即使在您不严格需要括号的情况下,如果您这样做,也可能会产生更易读的代码。

答案 1 :(得分:0)

SELECT queue.first_dealer, queue.second_dealer, queue.status
FROM queue
WHERE queue.status = 3
AND (queue.first_dealer = $user_id OR queue.second_dealer = $user_id)
AND queue.first_dealer != queue.second_dealer
AND queue.status = 3
ORDER BY id DESC
LIMIT 5

答案 2 :(得分:0)

您应该在WHERE声明中使用括号:

WHERE queue.status = 3 and
      (queue.first_dealer = $user_id OR queue.second_dealer = $user_id)

如果您不希望它们相同,只需添加另一个子句:

WHERE queue.status = 3 and
      (queue.first_dealer = $user_id OR queue.second_dealer = $user_id) and
      queue.first_dealer <> queue.second_dealer