简体   繁体   English

检索查询中的最新日期

[英]retrieve the most recent date within a query

I was able to fix my previous query, however the results retrieve contains duplicates. 我能够解决以前的查询,但是结果检索包含重复项。 I want to retrieve the latest record. 我想检索最新记录。

For example: 例如:

   id | firstname | lastname | email             |  date
   1  | steven    | smith    | steven@gmail.com     2013-06-10 04:01:25
   2  | Bill      | Johnson  | bill@gmail.com    |  2014-06-10 04:01:25
   3  | steven    | smith    | steven@gmail.com  |  2014-10-10 12:01:25

The return result should be the row with IDs 2 and 3 THe ID 1 should be not returned as the date is older than the ID 3 date 返回结果应该是ID为2和3的行。由于日期早于ID 3日期,因此不应返回ID 1

How can I add this to the query below ? 如何将其添加到下面的查询中?

   SELECT
    users.firstname,
    users.lastname,
    DISTINCT(users.email),
    users.pref
   FROM (
    SELECT
        users.firstname,
        users.lastname,
        users.email,
        users.status,
         users.active,

        CONCAT(
            users.preference_1, ',',
            users.preference_2, ',', 
            users.preference_3
        ) AS pref
    FROM users
) AS users

  WHERE  users.status = 1
  AND users.active = 1
  AND users.date = (
SELECT MAX(u.date) FROM users AS u WHERE u.email =  users.email
  )
  LIMIT 10000
  1. no need for subselect 无需子选择
  2. add: ORDER BY users.date DESC LIMIT 1 this way you sort the list by date and return only the "1st elemet" which is the one with the "biggest/latest" date 添加: ORDER BY users.date DESC LIMIT 1这样,您可以按日期对列表进行排序,并仅返回日期为“最大/最新”的“第一要素”

Well, looks like you want to fetch the latest row for each user. 好吧,看来您想为每个用户获取最新行。

Here's a query that can do it. 这是一个可以做到的查询。 (It also uses subquery. I don't understand the necessity for using subquery to concat though) (它也使用子查询。不过,我不明白使用子查询进行连接的必要性)

SELECT DISTINCT us.email, us.preference FROM users AS us WHERE us.date = (
    SELECT MAX(u.date) FROM users AS u WHERE u.email = us.email
)

This does not fetch all the details you want. 这不会获取您想要的所有详细信息。 But gives you the basic idea about the query you might have to run. 但是为您提供了可能必须运行的查询的基本概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM