Why my mysql DISTINCT doesn't work ?

Posted by belaz on Stack Overflow See other posts from Stack Overflow or by belaz
Published on 2010-03-28T20:15:00Z Indexed on 2010/03/28 20:23 UTC
Read the original article Hit count: 148

Filed under:
|

Hello,

Why the two query below return duplicate member_id and not the third ?

i need the second query to work with distinct.

Anytime i run a GROUP BY, this query is incredibly slow and the resultset doesn't return the same value as distinct (the value is wrong).

SELECT member_id, id 
FROM ( SELECT * FROM table1 ORDER BY created_at desc ) as u 
LIMIT 5


+-----------+--------+
| member_id | id     |
+-----------+--------+
|     11333 | 313095 |
|    141831 | 313094 |
|    141831 | 313093 |
|     12013 | 313092 |
|     60821 | 313091 |
+-----------+--------+

SELECT distinct member_id, id 
FROM ( SELECT * FROM table1 ORDER BY created_at desc ) as u 
LIMIT 5

+-----------+--------+
| member_id | id     |
+-----------+--------+
|     11333 | 313095 |
|    141831 | 313094 |
|    141831 | 313093 |
|     12013 | 313092 |
|     60821 | 313091 |
+-----------+--------+

  SELECT distinct member_id
    FROM ( SELECT * FROM table1 ORDER BY created_at desc ) as u 
    LIMIT 5

+-----------+
| member_id |
+-----------+
|     11333 |
|    141831 |
|     12013 |
|     60821 |
|     64980 |
+-----------+

my table sample

CREATE TABLE `table1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `member_id` int(11) NOT NULL,
  `s_type_id` int(11) NOT NULL,
  `created_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `s_FI_1` (`member_id`),
  KEY `s_FI_2` (`s_type_id`)
) ENGINE=InnoDB AUTO_INCREMENT=313096 DEFAULT CHARSET=utf8;

© Stack Overflow or respective owner

Related posts about mysql

Related posts about php