0

我有一件很奇怪的事情要做,只是不知道该怎么做。这是我的表格及其数据:

+------+-----------+-------------+-------+------------+
| uid  | entity_id | entity_type | state | created    |
+------+-----------+-------------+-------+------------+
| 3913 |      1105 |           1 |     0 | 1340617072 |
| 3913 |      1105 |           1 |     1 | 1340617042 |
| 3913 |      3930 |           1 |     0 | 1340617071 |
| 3913 |      3930 |           1 |     1 | 1340617036 |
+------+-----------+-------------+-------+------------+

created保存已执行操作的时间戳,是操作state的状态(已关注或未关注),uid是执行操作的人,并且entity_id是正在关注/取消关注的实体 ID。

我正在尝试进行查询,以获取entity_id当前用户关注的所有信息。首先我使用的是:

SELECT entity_id FROM follow_objects WHERE uid=? AND entity_type=?

但是我注意到,如果我关注某人然后取消关注他们,我仍然会得到那个人的结果,因为它有 2 个条目(状态 = 1,然后状态 = 0)。

所以我需要获取具有最新created列的行,这意味着该操作是最新的。所以我试过:

SELECT entity_id FROM follow_objects WHERE uid=? AND entity_type=? group by entity_id HAVING created=MAX(created)

它只返回垃圾数据。我没主意了。有什么帮助吗?

4

2 回答 2

1

您需要按组选择最大值。您必须将最大值包装在子选择中,并在entity_ids 相等且子选择的最大时间戳等于创建的时间戳的地方加入表本身。结果是您将获得entity_id每组的顶行数据:

SELECT
    a.entity_id,
    b.state,
    b.created
FROM
    (
        SELECT entity_id, MAX(created) AS max_created
        FROM follow_objects
        WHERE uid = ? AND entity_type = ?
        GROUP BY entity_id
    ) a
INNER JOIN
    follow_objects b ON
        a.entity_id = b.entity_id AND
        a.max_created = b.created
于 2012-06-25T09:53:05.743 回答
0

首先选择所有匹配的行并按创建日期(最新的在前)对它们进行排序,然后从该结果中取第一个:

SELECT entity_id
FROM (
    select entity_id, created
    from follow_objects
    WHERE uid=?
    AND entity_type=?
    order by created desc
) x
limit 1

易于理解和编码。

仅供参考,括号后的“x”在那里,因为您需要为从中选择的所有结果集提供别名,所以我将其称为“x”。

于 2012-06-25T09:58:43.260 回答