Vorrei chiedere aiuto per risolvere il problema con l'ordinamento della struttura gerarchica dei dati archiviata come tabella di chiusura .Ordinamento di una sottostruttura in una struttura gerarchica di dati della tabella di chiusura
Volevo utilizzare questa struttura per memorizzare il menu del mio sito web. Tutto funziona bene, ma il problema è che non so come ordinare la sottostruttura esatta in un ordine personalizzato . Al momento la struttura dell'albero viene ordinata nell'ordine in cui gli articoli sono stati aggiunti al database.
La mia struttura si basa su Bill Karwin's article su Tabelle di chiusura e alcuni altri post.
Qui è la mia struttura del database MySQL con alcuni dati DEMO:
--
-- Table `category`
--
CREATE TABLE IF NOT EXISTS `category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) COLLATE utf8_czech_ci NOT NULL,
`active` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
INSERT INTO `category` (`id`, `name`, `active`) VALUES
(1, 'Cat 1', 1),
(2, 'Cat 2', 1),
(3, 'Cat 1.1', 1),
(4, 'Cat 1.1.1', 1),
(5, 'Cat 2.1', 1),
(6, 'Cat 1.2', 1),
(7, 'Cat 1.1.2', 1);
--
-- Table `category_closure`
--
CREATE TABLE IF NOT EXISTS `category_closure` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`ancestor` int(11) DEFAULT NULL,
`descendant` int(11) DEFAULT NULL,
`depth` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_category_closure_ancestor_category_id` (`ancestor`),
KEY `fk_category_closure_descendant_category_id` (`descendant`)
) ENGINE=InnoDB;
INSERT INTO `category_closure` (`id`, `ancestor`, `descendant`, `depth`) VALUES
(1, 1, 1, 0),
(2, 2, 2, 0),
(3, 3, 3, 0),
(4, 1, 3, 1),
(5, 4, 4, 0),
(7, 3, 4, 1),
(8, 1, 4, 2),
(10, 6, 6, 0),
(11, 1, 6, 1),
(12, 7, 7, 0),
(13, 3, 7, 1),
(14, 1, 7, 2),
(16, 5, 5, 0),
(17, 2, 5, 1);
Qui è la mia query SELECT per un albero:
SELECT c2.*, cc2.ancestor AS `_parent`
FROM category AS c1
JOIN category_closure AS cc1 ON (cc1.ancestor = c1.id)
JOIN category AS c2 ON (cc1.descendant = c2.id)
LEFT OUTER JOIN category_closure AS cc2 ON (cc2.descendant = c2.id AND cc2.depth = 1)
WHERE c1.id = __ROOT__ AND c1.active = 1
ORDER BY cc1.depth
Per l'istanza DEMO con __ROOT_ = 1 che ottiene la query:
id name active _parent
1 Cat 1 1 NULL
3 Cat 1.1 1 1
6 Cat 1.2 1 1
4 Cat 1.1.1 1 3
7 Cat 1.1.2 1 3
E se, ad esempio, dovessi cambiare l'ordine di Cat 1.1 e Cat 1.2 (in base al nome o ad un ordine personalizzato)?
Ho visto qualche soluzione di breadcrumb (come ordinare per breadcrumb), ma non so come generarli e modificarli.
+1 grazie per la pubblicazione del campione DDL e dati. –