MySQL SQL Select 使一个值只出现一次
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7686049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL Select to make a value appear only once
提问by kurisukun
For those that have been helping me along the way with this twitter-clone, thank you!! With your help, I've managed to get most things working and finally now to the last steps of the followers function.
对于那些在此推特克隆过程中一直在帮助我的人,谢谢!!在您的帮助下,我已经设法使大多数事情正常工作,现在终于到了关注者功能的最后一步。
Right now, I have a dataset with the following fields: username, tweet, date
现在,我有一个包含以下字段的数据集:用户名、推文、日期
An example of the data could look like:
数据示例可能如下所示:
Username Tweet Date
kenny hi! 2011-10-07 19:07:00
stan hello 2011-10-05 18:07:00
kenny looks like rain 2011-10-05 17:07:00
stan hello 2011-10-05 14:07:00
cartman authoritay! 2010-10-05 14:07:00
And I've been wrestling with the SQL statement that would produce a data set in which each user appears only once with their latest tweet. So, based on the above, something that looks like this:
我一直在努力使用 SQL 语句,该语句会生成一个数据集,其中每个用户的最新推文只出现一次。因此,基于上述内容,看起来像这样:
Username Tweet Date
kenny hi! 2011-10-07 19:07:00
stan hello 2011-10-05 18:07:00
cartman authoritay! 2010-10-05 14:07:00
I've been googling sql searches and have tried variations of COUNT, DISTINCT, MAX, but to no avail. Any help would be greatly appreciated! Thank you!
我一直在谷歌搜索 sql 搜索并尝试过 COUNT、DISTINCT、MAX 的变体,但无济于事。任何帮助将不胜感激!谢谢!
回答by JB Nizet
select d1.username, d1.tweet, d1.date from data d1 where d1.date =
(select max(d2.date) from data d2 where d1.username = d2.username)
回答by Christian Watteng?rd
Would it not work just by
难道它不工作只是通过
select distinct username, tweet, date order by date desc
(This is MSSQL syntax)
(这是 MSSQL 语法)
With new data in hand:
手头有新数据:
SELECT DISTINCT tweets.username, content, date from tweets
WHERE user_id IN (
SELECT users.id FROM users
INNER JOIN user_users ON users.id = user_users.followed_user_id
WHERE user_users.user_id = 1)
ORDER BY date desc
回答by Shakti Singh
SELECT f.*
FROM (
SELECT Username, MAX(`Date`) as maxval
FROM table GROUP BY Username
) AS x INNER JOIN table AS f
ON f.Username = x.Username AND f.`Date`= x.maxval