简体   繁体   中英

MySQL single query with parent child relation stored across tables

I have a table as

table1

| ID | Description  | Type   |
| 1  | Desc 1       | type1  |
| 2  | Desc 2       | type1  |
| 3  | Desc 11      | type1  |
| 4  | Desc 21      | type1  |
| 5  | Desc 12      | type1  |
| 6  | Desc 31      | type1  |
| 7  | Desc 3       | type1  |
| 8  | Desc 111     | type1  |
| 9  | Desc 112     | type1  |

relationtable1
table1.id <-> relationtable1.rel_to_id and table1.id <-> relationtable1.rel_from_id

| ID | rel_to_id | rel_from_id  | relation   |
| 1  |    3      | 1            | parent     |
| 2  |    4      | 2            | parent     |
| 3  |    5      | 1            | parent     |
| 4  |    6      | 7            | parent     |
| 5  |    8      | 3            | parent     |
| 6  |    9      | 3            | parent     |

Please help me with a mysql query which will yield me the Expected Result :

| ID | Description  | Type   |
| 1  | Desc 1       | type1  |
| 3  | Desc 11      | type1  |
| 8  | Desc 111     | type1  |
| 9  | Desc 112     | type1  |
| 5  | Desc 12      | type1  |
| 2  | Desc 2       | type1  |
| 4  | Desc 21      | type1  |
| 7  | Desc 3       | type1  |
| 6  | Desc 31      | type1  |

SQL FIDDLE

Unfortunately, the relation table you provided (issuerelationtable) is not a valid Clousure table for generating adjacent list. Here's how it should be storing references..

CREATE TABLE `issuerelationtable` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `rel_to_id` int(11) DEFAULT NULL,
  `rel_from_id` int(11) DEFAULT NULL,
  `relation` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=18 ;



INSERT INTO `issuerelationtable` (`id`, `rel_to_id`, `rel_from_id`, `relation`) VALUES
(1, 1, 1, NULL),
(2, 3, 1, NULL),
(3, 5, 1, NULL),
(4, 8, 1, NULL),
(5, 9, 1, NULL),
(6, 2, 2, NULL),
(7, 4, 2, NULL),
(8, 4, 4, NULL),
(9, 3, 3, NULL),
(10, 8, 3, NULL),
(11, 9, 3, NULL),
(12, 5, 5, NULL),
(13, 6, 6, NULL),
(14, 7, 7, NULL),
(15, 6, 7, NULL),
(16, 8, 8, NULL),
(17, 9, 9, NULL);

To achieve the desired output, query should be..

SELECT
  DISTINCT(it.id),
  it.description,
  it.type
FROM
  issuetable it
  INNER JOIN issuerelationtable irt ON it.id=irt.rel_from_id
WHERE
  irt.rel_to_id IN (SELECT id FROM issuetable)
ORDER BY
  it.description

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM