SQL:如何在忽略重复字段值的同时从表中选择行?

时间:2021-10-22 12:54:25

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个最近活跃的用户。问题是,以下脚本选择了Peter两次。

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.

我想要的是当它再次到达Peter时跳过该行,并选择下一个结果,在我们的例子中是Adam。因此,我不想向访问者展示最近活跃的用户是Laura,Tom,Josh,Peter和Peter。这没有任何意义,相反,我想以这种方式向他们展示:劳拉,汤姆,乔希,彼得,(跳过彼得)和亚当。

Is there an SQL command i can use for this problem?

是否有可以用于此问题的SQL命令?

2 个解决方案

#1


26  

Yes. "DISTINCT".

是。 “不同”。

 SELECT DISTINCT(user_id) FROM messages ORDER BY id DESC LIMIT 5

#2


2  

Maybe you could exclude duplicate user using GROUP BY.

也许你可以使用GROUP BY排除重复的用户。

SELECT * FROM messages GROUP BY user_id ORDER BY id DESC LIMIT 5;

#1


26  

Yes. "DISTINCT".

是。 “不同”。

 SELECT DISTINCT(user_id) FROM messages ORDER BY id DESC LIMIT 5

#2


2  

Maybe you could exclude duplicate user using GROUP BY.

也许你可以使用GROUP BY排除重复的用户。

SELECT * FROM messages GROUP BY user_id ORDER BY id DESC LIMIT 5;