仅在某个字段高于0时才加入

时间:2013-11-23 03:38:27

标签: sql

这是为了查找一名球员,现在如果他们不是公会成员就会回来。因此,如果ranks大于零,那么只有guildsp.rank_id才能加入,而不是几个查询?

如果可能的话会很棒!

SELECT 
  p.id, 
  p.name, 
  p.sex, 
  p.level, 
  p.city, 
  p.last_login, 
  p.comment, 
  p.skill, 
  r.name AS rank, 
  g.name AS guild 
FROM 
  players p 
INNER JOIN 
  ranks r 
ON 
  r.id = p.rank_id 
INNER JOIN 
  guilds g 
ON 
  g.id = r.guild_id 
WHERE 
  p.name = :name

2 个答案:

答案 0 :(得分:0)

当然可以。添加

AND p.rankid > 0 

到您的WHERE子句,如

WHERE 
  p.name = :name AND p.rankid > 0

答案 1 :(得分:0)

尝试UNION ALL之类的:

SELECT p.id,  p.name, p.sex, p.level, p.city, p.last_login, p.comment, p.skill, r.name AS rank, g.name AS guild 
FROM players p 
INNER JOIN ranks r 
ON r.id = p.rank_id 
INNER JOIN guilds g 
ON g.id = r.guild_id 
WHERE p.name = :name and p.rankid>0
UNION ALL
SELECT p.id,  p.name, p.sex, p.level, p.city, p.last_login, p.comment, p.skill, '' AS rank, '' AS guild 
FROM players p
WHERE p.name = :name and p.rankid=0