2017-06-22 60 views
0

我写了这个查询,但它似乎是一个非常糟糕的查询,缩短MySQL的情况下查询

select * from games_applied where 
games_post_id='1126' and status != '4' and 
(status != '5' and rejected_status = '0' or status = '5' and rejected_status = '1'); 

如何利用这种情况下的一种更好的方式。

(status != '5' and rejected_status = '0' or status = '5' and rejected_status = '1') 

应该只显示其具有rejected_status = 1个状态= 5 并且不应该显示其具有rejected_Status = 0和状态= 5

+0

能否请您给一个小的描述,你希望得到尽可能输出什么?请添加表结构,以便它更有帮助。 –

+0

*但它似乎是一个非常糟糕的查询* - ***为什么?*** – iamdave

+0

@iamdave在我看来,这是一个糟糕的查询 – dude

回答

1

这不是一个大的行的行简化,但它确实删除了与4的比较。然而,这是我会怎么写查询:

select ga.* 
from games_applied ga 
where ga.games_post_id = 1126 and 
     ((ga.status not in (4, 5) and ga.rejected_status = 0) or 
     (ga.status = 5 and ga.rejected_status = 1) 
    ); 

注:

  • 表有一个有意义的表的别名。
  • 所有列名都是合格的。
  • 我认为这些数字实际上是数字列的比较,所以我删除了单引号。
  • 我将比较删除为“4”。
1

您的查询需要的唯一改进就是封装您的或语句两边的两个子句。换句话说,把你的statusrejected_status检查在括号内。

select 
    * 
from 
    games_applied 
where 
    games_post_id='1126' 
    and status != '4' 
    and 
    (
     (status != '5' and rejected_status = '0') 
     or (status = '5' and rejected_status = '1') 
    ); 
0

下面是该查询希望它的工作原理是必需的:

select * from games_applied where 
games_post_id='1126' and status != '4' and case when status='5' then 
rejected_status='1' else rejected_status='0' end;