在mysql中结合CASE和LIMIT

时间:2014-05-25 12:10:33

标签: mysql

假设我有一个与此结构类似的表:

字段1 |场2 |第3场

  

1 - - - - - 4 - - - - thisone

     

2 - - - - - 3 - - - - this_will_be_selected

     

3 - - - - - 2 - - - - this_will_be_selected

     

4 - - - - - 2 - - - - this_will_be_selected

     

1 - - - - - 4 - - - - this_one_could_also_be 而不是第一个

     

6 - - - - - 4 - - - - this_will_be_selected 因为没有其他field2 = 4 AND field1 = 6

我想做的是每当field2在查询中获得 ALL field3 when field2!= 4 限制1 = 4

所以,对于这个查询,我会得到:

field1 = 1 field3 = thisone

field1 = 2 field3 = this_will_be_selected

field1 = 3 field3 = this_will_be_selected

field1 = 4 field3 = this_will_be_selected

field1 = 6 field3 = this_will_be_selected

field1 = 1及其字段3" this_one_could_also_be" 未被选中

我希望自己清楚明白!

我的想法与此类似:

SELECT field1, field3 FROM table WHERE LIMIT (CASE field2 WHEN 0 THEN 1 ELSE ...;

显然问题是它会限制检索到的行数总数但我喜欢的是DISTINCT和field2但我不是了解我应该怎么做......

1 个答案:

答案 0 :(得分:0)

看起来这就是你之后的事情:

SELECT field3 FROM MyTable
WHERE field2 != 4
UNION ALL
SELECT MAX(field3) FROM MyTable
WHERE field2 = 4
GROUP BY field1;

MAX()函数可以任意选择要显示的field3。 GROUP BY确保每个不同的field1只返回一行,其中field2为4.