2014-03-07 99 views
2

比方说,我有一个名为表“消息”:ORDER BY先提,然后由另一列

+-----------+--------+ 
| timestamp | poster | 
+-----------+--------+ 
|   1 | John | 
|   2 | Peter | 
|   3 | Peter | 
|   4 | Chris | 
|   5 | John | 
+-----------+--------+ 

我希望所有帖子的第一张海报,则全部由第二张海报的查询到第一单等而不使用子查询。第一张海报由时间戳确定。找出谁是第一,并返回其所有的职位,那么谁是第二:

+-----------+--------+ 
| timestamp | poster | 
+-----------+--------+ 
|   1 | John | 
|   5 | John | 
|   2 | Peter | 
|   3 | Peter | 
|   4 | Chris | 
+-----------+--------+ 

编辑
好球员,我提出这个问题的方式太简单了。因为(J)ohn之前(P)eter,所以你给的工作非常基本。如果彼得是第一个呢?您需要将DESC添加到海报条款中。使用简单的ORDER BY你的SQL语句不应对谁是第一,第二,第三排序的问题,等等。

再次编辑
我补充说:“克里斯”的组合,以使其更平原到我想要的。约翰是第一张海报;获取他所有的帖子。彼得,因为他是第二。然后Chris。

+0

哪里是'timestamp'列? –

+0

你可以在这里学习一些基础http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization。html – jomsk1e

+0

@Prix,更改了链接XD – jomsk1e

回答

1

我觉得有没有其他办法,而不是创建另一个结果集,并与加盟:

SELECT poster, MIN(timestamp) AS first_ts 
FROM messages 
GROUP BY poster 
ORDER BY first_ts; 

结果:

+--------+-----------+ 
| poster | first_ts | 
+--------+-----------+ 
| John | 1   | 
| Peter | 2   | 
| Chris | 4   | 
+--------+-----------+ 
+0

您能提供一个如何加入您的查询以提供所需结果集的例子吗?或者你是指在应用程序中进行循环? – JFriend

0

使用ORDER BY

SELECT * FROM my_table ORDER BY poster ASC; 
0

什么@Deepak写的扩展,你需要在ORDER BY

SELECT timestamp, poster 
FROM my_table 
ORDER BY poster, timestamp; 

两个字段这会给你的第二个表。

0

尝试......

SELECT * 
FROM TableName 
ORDER BY poster ASC, 
      timestamp ASC; 

或者干脆...

SELECT * 
FROM TableName 
ORDER BY poster, 
      timestamp; 

如果不指定排序顺序,SQL自动假定ASC或上升,否则,加DESC为降。

0

试试这个:

SELECT * FROM messages ORDER BY timestamp ASC, poster ASC; 

请阅读更多here

1

不能想想办法,而不子查询做,

,但如果你能接受你的答案为csv列表的时间戳。那么这里是一种方式。

SELECT poster, 
     GROUP_CONCAT(timestamp ORDER BY timestamp) as timestamps  
FROM messages 
GROUP BY poster 
ORDER BY MIN(timestamp) 

sqlFiddle

相关问题