[英]MySql get value of default or min row
I have a table with structure 我有一张有结构的桌子
ID|GROUP_ID|DEFAULT|VALUE
13| 10| 0| 20
14| 11| 0| 30
15| 10| 0| 40
16| 10| 1| 50
17| 11| 0| 60
I want to get one row for each GROUP_ID by rule: 我想按规则为每个GROUP_ID获取一行:
if GROUP_ID has row with DEFAULT = 1 I have to get this row 如果GROUP_ID有DEFAULT = 1的行,我必须得到这一行
if GROUP_ID doesn't have row with DEFAULT = 1 I have to get row with MIN(VALUE) 如果GROUP_ID没有DEFAULT = 1的行,我必须以MIN(VALUE)的行
For above data result should be: 对于上述数据,结果应为:
16|10|1|50
14|11|0|30
How can I do this with MySql? 我该如何使用MySql?
You can do this in MySQL. 您可以在MySQL中执行此操作。 Here is one method: 这是一种方法:
select t.*
from t
where t.id = (select t2.id
from t t2
where t2.group_id = t.group_id
order by (default = 1) desc, value asc
limit 1
);
The subquery orders all rows for a given group based on your rules. 子查询根据您的规则对给定组的所有行进行排序。 The expression (default = 1) desc
, put the default values first. 表达式(default = 1) desc
,将默认值放在第一位。 In a numeric context, MySQL treats boolean values as numbers, with "1" for true and "0" for false (hence the desc
). 在数字上下文中,MySQL将布尔值视为数字,其中“ 1”为true,“ 0”为false(因此为desc
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.