假设我们有两个表与1到n的关系
group
--+-------+
id|name |
--+-------+
1 | GROUP1|
2 | GROUP2|
3 | GROUP3|
--+-------+
unit
--+-----+-----+------+
id|group|value|status|
--+-----+-----+------+
1| 1 | 0 | 0 |
2| 1 | 20 | 0 |
3| 1 | 5 | 0 |
4| 2 | 1 | 1 |
5| 2 | 3 | 1 |
6| 2 | 0 | 1 |
7| 3 | 5 | 1 |
8| 3 | 8 | 0 |
9| 3 | 6 | 0 |
我怎么知道,如果某一行在组中是唯一的?如果不是唯一的,它有什么价值? 例如:
SELECT
DISTINCT `group`.id,
`group`.name,
MIN(unit.value) AS 'min',
MAX(unit.value) AS 'max',
isUnique(unit.status) AS 'status'
FROM unit JOIN `group` ON unit.`group` = `group`.id
GROUP BY `group`.id
ORDER BY `group`.id
应该返回:
--+-------+---+---+------+
id|name |min|max|status|
--+-------+---+---+------+
1 | GROUP1|0 |20 | all 0|
2 | GROUP2|0 |3 | all 1|
3 | GROUP3|5 |8 | both |
(status is in string just to ilustarate returned values)
答案 0 :(得分:2)
您可以GROUP_CONCAT
使用每组不同的状态
SELECT
DISTINCT `group`.id,
`group`.name,
MIN(unit.value) AS 'min',
MAX(unit.value) AS 'max',
GROUP_CONCAT(DISTINCT unit.status) AS 'status'
FROM unit JOIN `group` ON unit.`group` = `group`.id
GROUP BY `group`.id
ORDER BY `group`.id
结果将是
--+-------+---+---+------+
id|name |min|max|status|
--+-------+---+---+------+
1 | GROUP1|0 |20 | 0 |
2 | GROUP2|0 |3 | 1 |
3 | GROUP3|5 |8 | 1,0 |
答案 1 :(得分:1)
试试这个
SELECT
DISTINCT `group`.id,
`group`.name,
MIN(unit.value) AS 'min',
MAX(unit.value) AS 'max',
CASE WHEN MAX(unit.status) = MIN(unit.status)
Then unit.status Else 'Both' END AS 'status'
FROM unit JOIN `group` ON unit.`group` = `group`.id
GROUP BY `group`.id
ORDER BY `group`.id