为什么下面的两个查询返回重复的member_id而不是第三个?
我需要第二个查询才能使用distinct。无论何时我运行 GROUP BY ,此查询都非常慢,并且结果集不会返回与distinct相同的值(值是错误的)。
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 |
+-----------+
我的表格样本
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;
答案 0 :(得分:17)
DISTINCT
是一个关键字,您只能在整个SELECT
上应用,而不能在单个字段上应用。它确保数据库不返回两个相同的行。这就是为什么第二次使用DISTINCT
查询时,每次member_id
只返回一次,而第一次返回时则为member_id
。在其结果集中,每行确实是唯一的,即使您可以获得相同{{1}}的几倍。
答案 1 :(得分:2)
它有效,它很脏(没有索引,没有键,临时表......)但是它可以工作,
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 :(得分:1)
在第一个查询中,没有明确的关键字。在第二个查询中,它选择不同的行。不是明确的成员ID。在第三个查询中,只有成员标识,因此它选择了不同的成员ID
答案 3 :(得分:1)
SELECT distinct member_id,id FROM(SELECT * FROM table1 ORDER BY created_at desc)为u 限制5
member_id
不是唯一的。这样查询会显示更多行...
答案 4 :(得分:0)
创建以下索引:
CREATE INDEX ix_table1_createdat ON table1 (created_at);
CREATE INDEX ix_table1_memberid_createdat ON table1 (member_id, created_at);
并使用此查询:
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
)