我有这样一个MYSQL表
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`screen_name` text NOT NULL,
`user_no` int(20) NOT NULL,
`avatar` text NOT NULL,
`name` varchar(50) NOT NULL,
`location` varchar(50) DEFAULT NULL
PRIMARY KEY (`id`)
我需要创建一个SQL查询。
id
DESC screen_name
id
我会分别比较嵌套查询和 JOIN查询的效果。
你能提出查询词吗?
谢谢
编辑:对于嵌套查询,我试过这个:
SELECT `name`,`screen_name` FROM `mytable` WHERE `id` IN
(SELECT `id` FROM `mytable` WHERE `id` BETWEEN 100 AND 500 ORDER BY `id` DESC)
GROUP BY `screen_name`
我无法为连接类型编写。
Edit2:说我有这样的行:
我需要得到这样的结果:
ID = 4
ID = 3
id = 1
答案 0 :(得分:2)
您的查询应采用以下格式:
SELECT MAX(id) AS max_id, user_no, screen_name
FROM table_name
WHERE id BETWEEN $idmin AND $idmax
GROUP BY screen_name
ORDER BY MAX(id) DESC;
或使用子查询:
SELECT a.id, a.name, a.screen_name
FROM example a
INNER JOIN (SELECT screen_name, MAX(id) id
FROM example
WHERE id BETWEEN 1 AND 4
GROUP BY screen_name
) b
ON a.screen_name = b.screen_name
AND a.id = b.id
ORDER BY a.id DESC;