SELECT DISTINCT不返回不同的值

时间:2012-08-21 12:48:15

标签: mysql sql

我有以下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?

3 个答案:

答案 0 :(得分:3)

因为时间戳不同。 DISTINCT适用于整行,而不仅仅是一列。

这会将您的时间戳截断为仅日期,然后890将不会重复。像NikolaMarkovinović建议的那样。

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

Manual entry for 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

答案 1 :(得分: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

答案 2 :(得分: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地址。