Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: How to select rows from a table while ignoring the duplicate field values?

Tags:

sql

mysql

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.

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.

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

like image 340
Maxxon Avatar asked Jan 13 '11 16:01

Maxxon


People also ask

How do I ignore duplicate rows in SQL?

Ignore duplicate rows in SQL. I think this may help you. SELECT res2.* FROM (SELECT res1.*,ROW_NUMBER () OVER (PARTITION BY res1.title ORDER BY res1.id)as num FROM (select * from [dbo]. [tbl_countries])as res1 )as res2 WHERE res2.num=1

How do you select duplicates in a table in SQL?

The first product is repeated two times in the table, while the second appears three times. To select duplicate values, you need to create groups of rows with the same values and then select the groups with counts greater than one. You can achieve that by using GROUP BY and a HAVING clause.

Does distinct remove duplicates in SQL?

Note that SQL treats every row of a result set as an individual record, and DISTINCT will only eliminate duplicates if multiple rows share identical values in each column To illustrate this, issue the following query that includes the DISTINCT keyword but returns both the name and park columns:

How to find duplicate entry in Oracle?

Having Clause is the easiest way to find duplicate entry in Oracle and using rowid we can remove duplicate data.. Show activity on this post. Ignore duplicate rows in SQL.


2 Answers

Yes. "DISTINCT".

 SELECT DISTINCT(user_id) FROM messages ORDER BY id DESC LIMIT 5
like image 162
Nanne Avatar answered Oct 18 '22 06:10

Nanne


Maybe you could exclude duplicate user using GROUP BY.

SELECT * FROM messages GROUP BY user_id ORDER BY id DESC LIMIT 5;
like image 30
yvoyer Avatar answered Oct 18 '22 05:10

yvoyer