Mysql
 sql >> डेटाबेस >  >> RDS >> Mysql

MySQL:विशिष्ट नोड में पत्ते कैसे खोजें

एक ही प्रश्न में ऐसा करने का कोई तरीका नहीं है। अगर होता भी तो शायद यह बहुत अक्षम होता।

हम इसे एक संग्रहीत प्रक्रिया और एक लूप के साथ कर सकते हैं। आपके द्वारा जोड़े गए इंडेक्स के साथ यह भी बहुत तेज़ होना चाहिए। यह इनपुट तालिका (ए) से नोड्स का चयन करने वाली दो तालिकाओं का उपयोग करता है और नोड और उनके बच्चों को (बी) में सम्मिलित करता है। यह तब ए के लिए बी को स्वैप करता है, और तब तक दोहराता है जब तक ए में कोई गैर-पत्ती नोड मौजूद नहीं होता है। अच्छी बात यह है कि लूप पुनरावृत्तियां केवल उतनी ही होंगी जितनी इनपुट नोड और अंतिम पत्ती नोड के बीच के स्तर हैं, जो कि ज्यादातर मामलों में है शायद उतना गहरा नहीं। यह संग्रहीत कार्यविधि बाहरी रूप से कोड में करने की तुलना में तेज़ होगी।

एफवाईआई मुझे अस्थायी तालिकाओं को संभालने में मेरी स्थापना में कठिनाई हुई, अगर आपको 'त्रुटि 2' मिलती है तो अस्थायी कीवर्ड हटा दें।

delimiter $$
drop procedure if exists GetLeafNodes $$
create procedure GetLeafNodes(nodeid int)
begin
declare N int default 1;

-- create two working sets of IDs, we'll go back and forth between these two sets
drop temporary table if exists A;
drop temporary table if exists B;
create temporary table A(node int, child int);
create temporary table B(node int, child int);

-- insert our single input node into the working set
insert into A values (null, nodeid);

while (N>0) do
  -- keep selecting child nodes for each node we are now tracking
  -- leaf nodes will end up with the child set to null
  insert into B
  select ifnull(A.child,A.node), tree.ID
    from A
    left outer join DATA_TREE as tree on A.child=tree.parent_id;

  -- now swap A and B
  rename table A to temp, B to A, temp to B;

  -- remove non-leaf nodes from table B
  delete from B;

  -- exit when there are no longer any non-leaf nodes in A
  set N=(select count(*) from A where child is not null);
end while;

-- now output our list of leaf nodes
select node from A;

drop temporary table A;
drop temporary table B;
end $$
DELIMITER ;
call GetLeafNodes(4);

मैंने परीक्षण के लिए निम्नलिखित नमूना सेट का उपयोग किया:

CREATE TABLE `DATA_TREE` (
  `ID` int(11) NOT NULL,
  `PARENT_ID` int(11) NOT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `ID_UNIQUE` (`ID`),
  KEY `fk_DATA_TREE_1_idx` (`PARENT_ID`)
) ENGINE=InnoDB
;

insert into DATA_TREE values
(1,0),(2,1),(3,1),(4,1),(5,3),(6,3),(7,4),(8,4),(9,4),(10,6),(11,6),(12,7),(13,9),(14,9),(15,12),(16,12),(17,12),(18,14);



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. क्या mysql में डुप्लिकेट इंडेक्स के लिए कार्डिनैलिटी भिन्न हो सकती है?

  2. SQL कर्सर के साथ कार्य करना

  3. लाइब्रेरी लोड नहीं हुई:mysql2 मणि ​​के साथ OS X 10.6 पर 'रेल सर्वर' चलाने का प्रयास करते समय libmysqlclient.16.dylib त्रुटि

  4. MySQL 5.7.10 में JSON डेटा टाइप कॉलम को कैसे अपडेट करें?

  5. MySQL में एक्सेंट कैसे निकालें?