Why is my mysql DISTINCT not working?

Why do the two queries below return a duplicate member_id and not the third?

I need a second request to work with different ones. Each time I run GROUP BY , this query is incredibly slow, and the result set does not return the same value as the value (the value is incorrect).

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 example table

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;
+3
source share
5 answers

it works, its dirty (no index, no key, temporary table ...), but it works,

SELECT member_id,id 
FROM ( SELECT member_id,id, created_at FROM table1 ORDER BY created_at desc ) as u 
group by member_id ORDER BY created_at desc LIMIT 5;
+2
source

DISTINCT - , SELECT, . , . DISTINCT member_id, . , member_id.

+17

. . . ,

+1

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

member_id . , ...

+1

Create the following indexes:

CREATE INDEX ix_table1_createdat ON table1 (created_at);
CREATE INDEX ix_table1_memberid_createdat ON table1 (member_id, created_at);

and use this query:

SELECT  t1i.*
FROM    (
        SELECT  DISTINCT member_id
        FROM    table1 tdi
        ORDER BY
                created_at DESC
        LIMIT 5
        ) t1d
JOIN    table1 t1i
ON      t1i.id =
        (
        SELECT  t1o.id
        FROM    table1 t1o
        WHERE   t1o.member_id = t1d.member_id
        ORDER BY
                t1o.member_id DESC, t1o.created_at DESC
        LIMIT 1
        )
0
source

Source: https://habr.com/ru/post/1738880/


All Articles