Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: SELECT DISTINCT multiple columns

Tags:

sql

mysql

My SQL query looks like this:

SELECT DISTINCT ip, title, url
FROM stats;

My goal is to select one row for each distinct ip, along with title and url; however I find when I add the title and url fields to my query it shows me all rows.

Sample Data

ip          title      url
---------------------------
127.0.0.1   title      url
127.0.0.2   title      url
127.0.0.1   difftitle  url

Result I would like

ip          title      url
---------------------------
127.0.0.1   title      url
127.0.0.2   title      url
like image 778
NotaGuruAtAll Avatar asked Jun 04 '26 12:06

NotaGuruAtAll


1 Answers

I think what you are looking for is a query like this -

SELECT 
    ip,
    title,
    url
FROM 
    stats
GROUP BY 
    ip 

GROUP BY is similar to DISTINCT - it means that all results will be grouped by ip, so it will only show one row of results for each distinct ip. However, nothing determines which record will be returned (e.g. which title and url will be shown).

There is no 'first' entry in the database - a relational database has no 'order' as such, unless you choose to order by a field.

like image 91
Eilidh Avatar answered Jun 06 '26 06:06

Eilidh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!