http://sqlfiddle.com/#!9/d865cf/2/1
架构:
c2
如果我立即开始CREATE TABLE IF NOT EXISTS `letters` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`letter` char(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
INSERT INTO `letters` (`id`, `letter`) VALUES
(1, 'd'),
(2, 'f'),
(3, 'a'),
(4, 'e'),
(5, 'c'),
(6, 'b');
CREATE TABLE IF NOT EXISTS `sort` (
`next` int(11) NOT NULL,
`prev` int(11) DEFAULT NULL,
PRIMARY KEY (`next`),
UNIQUE KEY `prev` (`prev`),
CONSTRAINT `fk` FOREIGN KEY (`next`) REFERENCES `letters` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;
INSERT INTO `sort` (`next`, `prev`) VALUES
(3, NULL),
(4, 1),
(6, 3),
(2, 4),
(1, 5),
(5, 6);
,我会收到订单select letter from letters
,但我希望不是d,f,a,e,c,b
的帮助,而是使用{{{}来获得字母顺序a,b,c,d,e,f
1}}表。如果您查看order by letter
表格中的条目,则sort
首先包含sort
因为id=3
,然后b next=3 and prev is null
为第二因为id=6
,则c为{ {1}}是第三位,因为next=6 and prev=3
等等。
如何使用MySQL中的其他表格执行自定义订单?
更新
我做到了,这可能是在mysql中执行此操作的唯一方法:
id=5
然后我按照预期得到next=5 and prev=6
:
DELIMITER //
CREATE PROCEDURE `custom_select`()
begin
declare v_next int;
declare v_letter char(1);
declare v_count tinyint;
DROP TEMPORARY TABLE IF EXISTS temp;
CREATE TEMPORARY TABLE temp (id int,letter char(1),idx int AUTO_INCREMENT,PRIMARY KEY (idx));
select id,letter,count(*) into v_next,v_letter,v_count from letters where sort=0;
while v_next is not null do
insert into temp(id,letter)values(v_next,v_letter);
select id,letter,count(*) into v_next,v_letter,v_count from letters where sort=v_next;
end while;
select id,letter from temp order by idx;
end//
DELIMITER ;
CREATE TABLE IF NOT EXISTS `letters` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`letter` char(1) DEFAULT NULL,
`sort` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `sort` (`sort`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;
DELETE FROM `letters`;
INSERT INTO `letters` (`id`, `letter`, `sort`) VALUES
(1, 'd', 5),
(2, 'f', 4),
(3, 'a', 0),
(4, 'e', 1),
(5, 'c', 6),
(6, 'b', 3);