Mysql首先停止所需的WHERE

时间:2016-03-12 14:37:06

标签: mysql where

让我说我有这样的说法:

select * from t1 join t2 on t1.id = t2.user_id where A OR B OR C ;

此查询将执行所有where条件并立即返回所有结果。我只想获得第一个 where子句的结果,该子句有结果,where子句的顺序是重要。我应该如何重写此查询以获得所需的结果?

2 个答案:

答案 0 :(得分:1)

如果您想订购结果,请使用order by

select *
from t1 join
     t2
     on t1.id = t2.user_id 
where A OR B OR C
order by (case when A then 1 when B then 2 when C then 3 end);

如果您想要一行,请将limit 1添加到此查询中:

select *
from t1 join
     t2
     on t1.id = t2.user_id 
where A OR B OR C
order by (case when A then 1 when B then 2 when C then 3 end)
limit 1;

如果你想要多行,那么我会计算每个条件的匹配行数,并在where中使用这些信息:

select *
from t1 join
     t2
     on t1.id = t2.user_id cross join
     (select sum(A) as num_A, sum(B) as num_B, sum(C) as num_C
      from t1 join
           t2
           on t1.id = t2.user_id 
     ) tt
where A or
      (num_A = 0 and B) or
      (num_A = 0 and num_B = 0 and C);

答案 1 :(得分:1)

试试这个:

protected Context mContext;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context ;
}

@Override
public void onDetach() {
super.onDetach();
mContext = null;
}