Question

So a little bit of a amateur question. I haven't worked too much with MySQL, but I need to pull a query from a table and I am not sure where I am going.

The table core_user has the following fields:

user_id
user_display_name
user_name
user_password
user_email
user_group
user_role
date_registered
language
timezone
region

I need to write a query to pull the following Columns:

user_display_name
user_name
user_password
user_email

Thing is there are sometimes up to 20 users that can have the same user_display_name. I only want the query to return one result per user_display_name. It doesn't matter who the user is but I can't have 20 people from the same company logging into my new module.

Can someone please give me a hand in writing this query. I have read about doing an SELF JOIN to do this, but I have no idea where to begin.

Was it helpful?

Solution

You can GROUP BY user_display_name field as follows;

SELECT user_display_name, user_name, user_password, user_email
FROM core_user
GROUP BY user_display_name

This works great for MySQL listing unique display names as you suggested in question description:

I only want the query to return one result per user_display_name

OTHER TIPS

You can use distinct to get only one result for all same username.
SELECT DISTINCT user_display_name, user_name, user_password, user_email
FROM core_user

From what I understand from your requirement, all you need to do is:

Select distinct user_display_name, user_name, user_password, user_email 
from core_user;

This will give all the unique result sets from the table.

The answer nes gave works great for MySql and is correct answer to the question.

I was just curious about how to do that in Sql Server since projecting a column that is not included in grouping is not allowed. So i came to accept this as a good solution;

DECLARE @table1 TABLE
(
  id int primary key,
  name nvarchar(50), 
  email nvarchar(50), 
  number int
) 

INSERT INTO @table1 VALUES (1, 'name1', 'a@a.com', 1)
INSERT INTO @table1 VALUES (2, 'name1', 'b@b.com', 2)
INSERT INTO @table1 VALUES (3, 'name2', 'c@c.com', 5)

SELECT t1.name, t1.number, t1.email 
FROM @table1 As t1 JOIN (SELECT name, MAX(id) As maxId FROM @table1 GROUP BY name) As t2
    ON t2.maxId = t1.id

Alias t2 is the result of subquery which returns the distinct names with additional column id information (MAX() is used as aggregate to guarantee there will only be one name and no duplicates, it could be MIN() aswell). t2 is joined with t1 on id fields ensuring that there will be unique names.

The only constraint is; there must be an id field or any other unique key

Just wanted to share, sorry if considered off-topic

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top