需要帮助排除MySQL中连接表中的某些行

时间:2014-01-18 21:23:02

标签: mysql

我有一个使用MySQL的游戏。我正在尝试显示最终游戏分数列表,此列表应排除用户已阻止的任何人。 以下是表格结构:

table_game
------------
table_id    int
person_id   int
person_nom  varchar(25)
finalscore  int
scoretime   datetime

table_blocked
--------------
table_id    int
person_id   int
person_id_blocked   int

假设我的person_id为'1'并且我已阻止person_id'5'(因此table_blocked中有一行,table_id = 1,person_id = 1,person_id_blocked = 5)。 这意味着我不应该在结果中看到person_id'5'。

这是查询,但是person_id'5'显示在结果中:

SELECT
  f.table_id,
  f.person_id as fID,
  f.person_nom AS fNOM,
  f.finalscore AS fFINAL,
  f.scoretime AS fTIME,
  table_blocked.table_id,
  table_blocked.person_id,
  table_blocked.person_id_blocked 
FROM
  table_game f 
  LEFT OUTER JOIN table_blocked ON f.person_id = table_blocked.person_id  
WHERE (
  (fFINAL > 0)
   AND ((table_blocked.person_id_blocked != '5') OR (table_blocked.person_id_blocked IS NULL))
)  
ORDER BY fTIME DESC 
LIMIT 5

我做错了什么?

1 个答案:

答案 0 :(得分:0)

嗯,是的。我认为编写查询的更清晰的方法是:

SELECT f.table_id, f.person_id as fID, f.person_nom AS fNOM, f.finalscore AS fFINAL,
       f.scoretime AS fTIME, table_blocked.table_id, table_blocked.person_id,   
       tb.person_id_blocked 
FROM table_game f
WHERE f.person_id not in (select person_id_blocked from table_blocked) and
      f.finalscore > 0

然后会变成:

SELECT f.table_id, f.person_id as fID, f.person_nom AS fNOM, f.finalscore AS fFINAL,
       f.scoretime AS fTIME, table_blocked.table_id, table_blocked.person_id,   
       tb.person_id_blocked 
FROM table_game f LEFT OUTER JOIN
     table_blocked tb
     ON f.person_id = tb.person_id_blocked
WHERE tb.person_id_blocked is null and
      f.finalscore > 0;