Basic Bridge
Basic Bridge

Reputation: 1911

Select Distinct value SQL

I have table like this

-------------------------------------------------------------------
id | title | image  | name |
-------------------------------------------------------------------
1  | xyzab | so.jpg | googl |
2  | acbde | am.jpg | artic |
3  | xyzab | pp.jpg | other |

i want to select unique or distinct title with it's image and name also. DO not want to repeat the values. I use this this code

SELECT DISTINCT title,image,name,id FROM `some_table`

but this is not working fine

NOTE: The OP is working with MySQL

Upvotes: 3

Views: 3222

Answers (3)

dwalldorf
dwalldorf

Reputation: 1379

DISTINCT is not applied to the one field after the keyword, but for fields in your select statement. What you're looking for is GROUP BY:

SELECT title,image,name,id FROM some_table GROUP BY title

Upvotes: 0

John Sobolewski
John Sobolewski

Reputation: 4572

You will need to specify the WINNER... in other words if there is a duplicate title but differening data in other columns you need to pick one...

For example you could try this.

select * from 'some_table' where id in (select min(id) from 'some_table' group by title)

Upvotes: 0

Curtis
Curtis

Reputation: 103358

Using DISTINCT will ensure no 2 records have all columns matching, so this is working correctly.

If you want to return unique titles, you need to decide what image and name would be returned.

You could use a group by with an aggregate function to do this. For example:

SELECT title, MIN(image), MIN(name), MIN(id)
FROM `some_table`
GROUP BY title

But it depends on what results you are after...

Upvotes: 5

Related Questions