【问题标题】:rows missing with group by added添加了 group by 的行丢失
【发布时间】:2013-08-15 07:16:35
【问题描述】:

这可能是我很菜的东西

我有下表

+------------+-------------+------+-----+---------+----------------+
| 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 只返回一行。

【问题讨论】:

  • 由于您正在应用 ORDER BY 子句,因此行为是正确的。请注意,ORDER BY 应用于所有结果,因此,由于按id 列排序,您将获得如您所写的结果。
  • 好吧,我只是想确认只返回一行“per from_id”

标签: mysql select group-by


【解决方案1】:

查询呢

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

希望这应该可行。

【讨论】:

  • sorryi 没有正确提到我确实希望每个“from_id”只有一行..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-30
  • 1970-01-01
  • 2014-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多