如何在嵌套的SQL查询中有条件?

时间:2010-05-12 16:24:06

标签: sql activerecord mysql

这是我的SQL语句,我想找到状态为0的所有游戏以及类似key_word或运动名称的团队名称,就像关键词一样。 问题是所有显示的游戏都没有状态0。 我做错了什么?

sql="select * from games where games.status=0 and games.team_2_id
     IN (select id from teams where name like '"+key_word+"')
      or games.team_1_id
        IN (select id from teams where name like '"+key_word+"')
          or games.sport like '"+key_word+"'
            "

1 个答案:

答案 0 :(得分:3)

看起来您只需将OR条件分别括在括号中:

SELECT * 
FROM   games 
WHERE  games.status = 0 AND 
       (games.team_2_id IN (SELECT id FROM teams WHERE name LIKE '%key_word%') OR
        games.team_1_id IN (SELECT id FROM teams WHERE name LIKE '%key_word%') OR
        games.sport LIKE '%key_word%')