1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
CREATE TABLE `groups` (
`group_id` int(11) NOT NULL AUTO_INCREMENT,
`group` varchar(45) NOT NULL,
PRIMARY KEY (`group_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
INSERT INTO `groups` (group_id,group) VALUES (1, 'group 1');
INSERT INTO `groups` (group_id,group) VALUES (2, 'group 2');
CREATE TABLE `items` (
`item_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`group_id` int(10) unsigned DEFAULT NULL,
`ident` varchar(45) NOT NULL,
PRIMARY KEY (`item_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
INSERT INTO `items` (item_id,group_id,ident) VALUES (1,NULL,'item 1, no group');
INSERT INTO `items` (item_id,group_id,ident) VALUES (2,1,'item 2, g1');
INSERT INTO `items` (item_id,group_id,ident) VALUES (3,2,'item 3, g1');
INSERT INTO `items` (item_id,group_id,ident) VALUES (4,1,'item 4, g1');
INSERT INTO `items` (item_id,group_id,ident) VALUES (5,NULL,'item 5, no group');
1
2
3
SELECT * FROM items i
LEFT JOIN groups g ON g.group_id = i.group_id
ORDER BY i.group_id DESC
2011-04-20T11:29:54 pktmDaraus hätte ich jetzt gerne eine Liste aller Items, sortiert nach Gruppe, wobei die ihne Gruppe zuerst kommen sollen.
ORDER BY IFNULL(i.group_id, 99999) DESC
1
2
3
SELECT * FROM items i
LEFT JOIN groups g ON g.group_id = i.group_id
ORDER BY ISNULL(i.group_id) DESC, i.group_id DESC