这是一个测试表
mysql> select * from test;
+----+---------+----------+
| id | content | content2 |
+----+---------+----------+
| 12 | a | 1 |
| 13 | a | 2 |
| 14 | a | 3 |
| 15 | a | 10 |
| 16 | a | 11 |
| 17 | a | 12 |
+----+---------+----------+
6 rows in set (0.00 sec)
我希望得到像这样的记录
+----+---------+------+------+
| id | content | a | b |
+----+---------+------+------+
| 12 | a | 3 | 12 |
+----+---------+------+------+
我想获得一条记录,选择不在所有数据中的东西
这是假代码:
mysql> select content,max(content2 where content2 < 5 oder by content2 DESC) AS a,
max(content2 where content2 < 15 oder by content2 DESC) AS b
from test
group by content
答案 0 :(得分:1)
drop table if exists t;
create table t(id int, content varchar(1), content2 int);
insert into t values
( 12 , 'a' , 1 ),
( 13 , 'a' , 2 ),
( 14 , 'a' , 3 ),
( 15 , 'a' , 10 ),
( 16 , 'a' , 11 ),
( 17 , 'a' , 12 );
select min(id) id ,content,
max(case when content2 < 5 then content2 else null end) a,
(select max(case when t2.content2 < 15 then t2.content2 else null end)
from t t2 where t2.content = t.content group by t2.content) b
from t
group by content
+------+---------+------+------+
| id | content | a | b |
+------+---------+------+------+
| 12 | a | 3 | 12 |
+------+---------+------+------+
1 row in set (0.00 sec)