MySQL查询嵌套或连接

时间:2012-08-28 10:04:24

标签: mysql sql database nested left-join

我有这样一个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查询。

  • ORDER BY id DESC
  • GROUP BY screen_name
  • 获取“name”和“screen_name”字段
  • $ limin和$ idmax之间的
  • 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 = 1,screen_name = mike,name = uk
  • id = 2,screen_name = albert,name = usa
  • id = 3,screen_name = ash,name = uk
  • id = 4,screen_name = albert,name = new_zelland

我需要得到这样的结果:
ID = 4
ID = 3
id = 1

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;

SQLFIDDLE DEMO HERE

或使用子查询:

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;

SQLFIDDLE DEMO HERE