假设我有一张表,其结构与此表类似:
栏位1 |栏位2 |领域3
1-----4----此人
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----因为没有其他field2 = 4 AND field1 = 6而选择了this_will_be_selected
我想做的是当field2!= 4时获得ALL field3,并在field2 = 4时在查询中限制1
因此,对于这一查询,我将获得:
栏位1 = 1
field3 =这个人
栏位1 = 2
field3 = this_will_be_selected
栏位1 = 3
field3 = this_will_be_selected
栏位1 = 4
field3 = this_will_be_selected
栏位1 = 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 ...;
问题显然是,这将限制总共检索到的行数,但是我想要的是带有field2的
DISTINCT
,但我不知道该怎么做... 最佳答案
看起来这就是您所追求的:
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。关于mysql - 在MySQL中结合CASE和LIMIT,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23855127/