有没有办法在mysql中选择包含where条件和order条件的字段
这是一张测试表有没有办法在mysql中选择包含where条件和order条件的字段,mysql,Mysql,这是一张测试表 mysql> select * from test; +----+---------+----------+ | id | content | content2 | +----+---------+----------+ | 12 | a | 1 | | 13 | a | 2 | | 14 | a | 3 | | 15 | a | 10 | | 16 | a |
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
ID12、A3和B12之间的相关性是什么?似乎完全是武断的。是的,这里只是一个例子。在实际情况中,content2是一个时间,我想在已筛选的数据中选择一些最长时间,比如2017/6/30之前记录的最新数据和2017/12/31之前记录的最新数据,我认为这是a的最小id,maxcontent2我找到了一个更简单的sql,我把它加在你的answer@afraid.jpg您不能编辑其他人的帖子并添加您的答案,如果您想代表您添加答案,请从下面添加一个单独的答案
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)