MySQL SQL:如何在忽略重复字段值的同时从表中选择行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4682621/
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: How to select rows from a table while ignoring the duplicate field values?
提问by Maxxon
How to select rows from a table while ignoring the duplicate field values?
如何在忽略重复字段值的同时从表中选择行?
Here is an example:
下面是一个例子:
id user_id message
1 Adam "Adam is here."
2 Peter "Hi there this is Peter."
3 Peter "I am getting sick."
4 Josh "Oh, snap. I'm on a boat!"
5 Tom "This show is great."
6 Laura "Textmate rocks."
What i want to achive is to select the recently active users from my db. Let's say i want to select the 5 recently active users. The problem is, that the following script selects Peter twice.
我想要实现的是从我的数据库中选择最近活跃的用户。假设我想选择 5 个最近活跃的用户。问题是,以下脚本选择了彼得两次。
mysql_query("SELECT * FROM messages ORDER BY id DESC LIMIT 5 ");
What i want is to skip the row when it gets again to Peter, and select the next result, in our case Adam. So i don't want to show my visitors that the recently active users were Laura, Tom, Josh, Peter, and Peter again. That does not make any sense, instead i want to show them this way: Laura, Tom, Josh, Peter, (skipping Peter) and Adam.
我想要的是当它再次到达彼得时跳过该行,并选择下一个结果,在我们的例子中是亚当。所以我不想再次向我的访问者展示最近活跃的用户是 Laura、Tom、Josh、Peter 和 Peter。这没有任何意义,相反,我想以这种方式向他们展示:劳拉、汤姆、乔希、彼得(跳过彼得)和亚当。
Is there an SQL command i can use for this problem?
是否有我可以用于解决此问题的 SQL 命令?
回答by Nanne
Yes. "DISTINCT".
是的。“清楚的”。
SELECT DISTINCT(user_id) FROM messages ORDER BY id DESC LIMIT 5
回答by yvoyer
Maybe you could exclude duplicate user using GROUP BY
.
也许您可以使用GROUP BY
.
SELECT * FROM messages GROUP BY user_id ORDER BY id DESC LIMIT 5;