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?
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
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.
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:
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.
Yes. "DISTINCT".
SELECT DISTINCT(user_id) FROM messages ORDER BY id DESC LIMIT 5
Maybe you could exclude duplicate user using GROUP BY
.
SELECT * FROM messages GROUP BY user_id ORDER BY id DESC LIMIT 5;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With