添加了缺少组的行

时间:2013-08-15 07:16:35

标签: mysql select group-by

这可能是我非常棒的事情

我有下表

+------------+-------------+------+-----+---------+----------------+
| Field      | Type        | Null | Key | Default | Extra          |
+------------+-------------+------+-----+---------+----------------+
| id         | int(11)     | NO   | PRI | NULL    | auto_increment |
| from_id    | int(11)     | YES  | MUL | NULL    |                |
| to_id      | int(11)     | YES  | MUL | NULL    |                |
| reply_cost | int(5)      | YES  |     | 0       |                |
| date       | timestamp   | YES  |     | NULL    |                |
| body       | text        | YES  |     | NULL    |                |
| read_      | char(1)     | YES  |     | 0       |                |
| trash      | tinyint(1)  | YES  | MUL | 0       |                |
| trashDate  | datetime    | YES  |     | NULL    |                |
| ip_address | varchar(20) | YES  |     | NULL    |                |
+------------+-------------+------+-----+---------+----------------+

选择

select id,from_id,to_id,date from mail where to_id='100' order by id desc limit 50;

返回

+----------+---------+-------+---------------------+
| id       | from_id | to_id | date                |
+----------+---------+-------+---------------------+
| 30071061 | 142     | 100   | 2013-08-15 04:39:56 |
| 30070785 | 282     | 100   | 2013-08-15 02:29:00 |
| 30064666 | 282     | 100   | 2013-08-14 16:10:39 |
| 30042809 | 458582  | 100   | 2013-08-12 15:50:45 |
| 30042560 | 458582  | 100   | 2013-08-12 15:28:39 |
| 30042557 | 458582  | 100   | 2013-08-12 15:28:22 |
| 30022845 | 458582  | 100   | 2013-08-10 17:32:40 |
| 30022834 | 458582  | 100   | 2013-08-10 17:31:22 |
| 30018276 | 458582  | 100   | 2013-08-10 06:09:27 |
| 30018275 | 458582  | 100   | 2013-08-10 06:09:00 |

但是像这样的选择

select id,from_id,to_id,date from mail where to_id='100' group by from_id order by id desc limit 50;

这样的输出(缺少from_id 282)

+----------+---------+-------+---------------------+
| id       | from_id | to_id | date                |
+----------+---------+-------+---------------------+
| 30017678 | 142     | 100   | 2013-08-10 01:56:38 |
| 29928935 | 189638  | 100   | 2013-07-31 18:33:01 |
| 29894382 | 458582  | 100   | 2013-07-27 22:15:53 |
| 29883054 | 409699  | 100   | 2013-07-26 15:22:35 |

任何想法如何避免这种情况?

编辑:忘记提及,目标是每个from_id只返回一行。

1 个答案:

答案 0 :(得分:0)

查询怎么样

select id,from_id,to_id,date from mail where to_id='100' order by id, from_id desc limit 50;

这应该可行,希望如此。