0

我有以下 MYSQL 来获取不同的 emails.to 值,但请参阅下面的结果

SELECT DISTINCT `emails`.`to`,`emails`.`from` as fromEmail, `emails`.`time` as timestamp
FROM `emails` 
WHERE ((`emails`.`from` = 'sdadr@googlemail.com') 
OR (`emails`.`to` = '887')) 
AND (`emails`.`to` != 0) 
ORDER BY `id` DESC LIMIT 4

-

to    fromEmail             timestamp
370   sdadr@googlemail.com  2012-08-15 16:52:15
1923  sdadr@googlemail.com  2012-08-15 10:54:48
890   sdadr@googlemail.com  2012-08-15 10:43:06
890   sdadr@googlemail.com  2012-08-15 10:43:02

为什么它会返回重复的 890?

4

3 回答 3

3

因为时间戳不同。这DISTINCT意味着整行,而不仅仅是一列。

这会将您的时间戳截断为仅日期,然后 890 不会重复。正如 Nikola Markovinović 所建议的那样。

SELECT DISTINCT `emails`.`to`,`emails`.`from` as fromEmail, DATE(`emails`.`time`) as timestamp
FROM `emails` 
WHERE ((`emails`.`from` = 'sdadr@googlemail.com') 
OR (`emails`.`to` = '887')) 
AND (`emails`.`to` != 0) 
ORDER BY `id` DESC LIMIT 4

如果您只想截断秒数,这也会导致所需的结果,您可以这样做:

SELECT DISTINCT `emails`.`to`,`emails`.`from` as fromEmail, 
DATE_FORMAT(`emails`.`time`, '%Y-%m-%d %H:%i') as timestamp
FROM `emails` 
WHERE ((`emails`.`from` = 'sdadr@googlemail.com') 
OR (`emails`.`to` = '887')) 
AND (`emails`.`to` != 0) 
ORDER BY `id` DESC LIMIT 4

手动输入以DATE_FORMAT()获取更多信息。

根据您的评论,如果您只想拥有唯一的电子邮件。只需选择该列,不要再使用DISTINCT.

SELECT DISTINCT `emails`.`to`
FROM `emails` 
WHERE ((`emails`.`from` = 'sdadr@googlemail.com') 
OR (`emails`.`to` = '887')) 
AND (`emails`.`to` != 0) 
ORDER BY `id` DESC LIMIT 4
于 2012-08-21T12:49:54.680 回答
0
SELECT DISTINCT `emails`.`to` 
  FROM `emails`  WHERE ((`emails`.`from` = 'sdadr@googlemail.com')  OR (`emails`.`to` = '887'))  AND (`emails`.`to` != 0)  
  ORDER BY `id` DESC LIMIT 4 

根据您的问题,您正在寻找to可以从此查询中获取的不同地址。

于 2012-08-21T12:53:10.097 回答
0

如前所述,截断至今:

SELECT DISTINCT `emails`.`to`,`emails`.`from` as fromEmail, DATE(`emails`.`time`) as timestamp
FROM `emails` 
WHERE ((`emails`.`from` = 'sdadr@googlemail.com') 
OR (`emails`.`to` = '887')) 
AND (`emails`.`to` != 0) 
ORDER BY `id` DESC LIMIT 4
于 2012-08-21T12:51:24.523 回答